0

I am building a Dockerfile where I pull a postgresq client. What I would like to do is to connect to the db and execute some sql commands (all defined in Dockerfile and with no interaction). If I execute something like this below, I am able to connect:

docker run -it --rm jbergknoff/postgresql-client postgresql://username:password@10.1.0.173:5432/db

but I do not know how to replicate this inside the Dockerfile:

FROM jbergknoff/postgresql-client
RUN  postgresql://username:password@10.1.0.173:5432/db // error

where the RUN command gives me error.

Stefano Maglione
  • 3,946
  • 11
  • 49
  • 96
  • Check this question: [Difference between RUN and CMD in a Dockerfile](https://stackoverflow.com/questions/37461868/difference-between-run-and-cmd-in-a-dockerfile) – tgogos Oct 22 '19 at 11:07

1 Answers1

1

The reason is very clear, Postgres service is not running at this stage I mean during the build time.

RUN postgresql://username:password@10.1.0.173:5432/db // error

So this will not work as you are expecting.

This is a common problem with such docker image or custom Docker, So I will suggest using offical image so you will not bother with custom entrypoint script and all you just need to copy your SQL script to /docker-entrypoint-initdb.d during build time or can mount to this path at runtime.

FROM postgres
COPY my_initdb.sql /docker-entrypoint-initdb.d/

That's it, the offical image will take care of this script and will run the script when the Postgres service is up and running.

If you want To make this working, you must place such command at entrypoint where the Postgres service is running and capable to handle the connection.

Initialization scripts

If you would like to do additional initialization in an image derived from this one, add one or more *.sql, *.sql.gz, or *.sh scripts under /docker-entrypoint-initdb.d (creating the directory if necessary). After the entrypoint calls initdb to create the default postgres user and database, it will run any *.sql files, run any executable *.sh scripts, and source any non-executable *.sh scripts found in that directory to do further initialization before starting the service.

Adiii
  • 54,482
  • 7
  • 145
  • 148
  • I have already a postgres container with a db, I just need this new container with a client to execute sql on the db container – Stefano Maglione Oct 22 '19 at 11:16
  • you can not connect with DB using RUN command, you must connect the DB from entrypoint or once it up. if you want to have same init data, just copy that file to `/docker-entrypoint-initdb.d ` and it will create container with this data. – Adiii Oct 22 '19 at 11:18
  • 1
    Ok, I got and where can I write command to execute (like select, etc)? – Stefano Maglione Oct 22 '19 at 11:20
  • Create a sql file and copy the file to docker-entrypoint-initdb.d at build time, it will be run automatically when the container is up – Adiii Oct 22 '19 at 11:29