10

Trying to make Dockerfile for postgres db need for my app.

Dockerfile

FROM postgres:9.4
RUN mkdir /sql
COPY src/main/resources/sql_scripts/* /sql/
RUN psql -f /sql/create_user.sql
RUN psql -U user -W 123 -f create_db.sql
RUN psql -U user -W 123 -d school_ats -f create_tables.sql

run

docker build .

result:

Sending build context to Docker daemon 3.367 MB
Step 1 : FROM postgres:9.4
 ---> 6196bca94565
Step 2 : RUN mkdir /sql
 ---> Using cache
 ---> 6f57c1e759b7
Step 3 : COPY src/main/resources/sql_scripts/* /sql/
 ---> Using cache
 ---> 3b496bfb28cd
Step 4 : RUN psql -a -f /sql/create_user.sql
 ---> Running in 33b2230a12fa
psql: could not connect to server: No such file or directory
    Is the server running locally and accepting
    connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?
The command '/bin/sh -c psql -a -f /sql/create_user.sql' returned a non-zero code: 2

How can I specify db in docker for my project?

1
  • 1
    The base dockerfile postgres:9.4 does not actually run postgres until the entry point is started. You need to start the container from the base image first. Commented May 2, 2016 at 6:24

2 Answers 2

13

When building your docker image postgres is not running. Database is started when container is starting, any sql files can be executed after that. Easiest solution is to put your sql files into special directory:

FROM postgres:9.4
COPY *.sql /docker-entrypoint-initdb.d/

When booting startup script will execute all files from this dir. You can read about this in docs https://hub.docker.com/_/postgres/ in section How to extend this image.

Also, if you need different user you should set environment variables POSTGRES_USER and POSTGRES_PASSWORD. It's easier then using custom scripts for creating user.

Sign up to request clarification or add additional context in comments.

1 Comment

According to the latest recommendations we should prefer to use COPY over ADD.
3

As the comment above says during the image build you don't get a running instance of Postgres.

You could take slightly different approach. Instead of trying to execute SQL scripts yourself you could copy them to /docker-entrypoint-initdb.d/ directory. They will be executed when the container starts up.

Have a look how postgres:9.4 image is build:

Also in your Dockerfile use variables to set database details:

  • POSTGRES_DB
  • POSTGRES_USER
  • POSTGRES_PASSWORD

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.