Having to insert the data every time you start a container can become a hassle. In this exercise we will create our own version of the Postgres image and bake our data into it. That way the data will always be available on startup.

The Postgres image provides a convenient way to execute scripts on startup of your database. All we have to do is add a .sh script to the docker-entrypoint-initdb.d-folder. Follow the steps below for detailed instructions.

If you still have containers running, please stop them now.

1. Build & run the image

custom db container

Follow the steps below to create your own version of the Postgres image, including the files necessary to create the data we will access from the webserver.

  • Create an empty folder

    1. Save the shell script below in that folder as create.sh

#!/bin/bash
set -e

psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" <<-EOSQL
    CREATE DATABASE mydata;
    \c mydata
    CREATE TABLE kv (key varchar(100) PRIMARY KEY, value varchar(100));
    INSERT INTO kv VALUES ('provider','Now getting data from Postgres!');
EOSQL
  • Create a Dockerfile in the folder that

    1. Is built from postgres:9

    2. Adds the .sh file to the docker-entrypoint-initdb.d folder in the container. Postgres will run any *.sql files and source any *.sh scripts found in this directory to do further initialization before starting the service.

  • Build the image with the name database

  • Run the newly build image as part of the training network

  • Run a webserver container and also make it part of the training network

You should see the message 'Now getting data from Postgres!' if you visit the web app.

On Windows you may have to run dos2unix on your .sh file before you can build the image. This will fix the line-endings in the script and allow it to be executed by the database image. Alternatively you can open the .sh file in Notepad++ and change the line endings to UNIX style.