0

I've created an image for docker which hosts a postgresql server. In the dockerfile, the environment variable 'USER', and I pass a constant password into the a run of psql:

USER postgres
RUN /etc/init.d/postgresql start && psql --command "CREATE USER docker WITH SUPERUSER PASSWORD 'docker';" && createdb -O docker docker

Ideally either before or after calling 'docker run' on this image, I'd like the caller to have to input these details into the command line, so that I don't have to store them anywhere.

I'm not really sure how to go about this. Does docker have any support for reading stdin into an environment variable? Or perhaps there's a better way of handling this all together?

Andy
  • 3,228
  • 8
  • 40
  • 65

2 Answers2

1

At build time

You can use build arguments in your Dockerfile:

ARG password=defaultPassword
USER postgres
RUN /etc/init.d/postgresql start && psql --command "CREATE USER docker WITH SUPERUSER PASSWORD '$password';" && createdb -O docker docker

Then build with:

$ docker build --build-arg password=superSecretPassword .

At run time

For setting the password at runtime, you can use an environment variable (ENV) that you can evaluate in an entrypoint script (ENTRYPOINT):

ENV PASSWORD=defaultPassword
ADD entrypoint.sh /docker-entrypoint.sh
USER postgres
ENTRYPOINT /docker-entrypoint.sh
CMD ["postgres"]

Within the entrypoint script, you can then create a new user with the given password as soon as the container starts:

pg_ctl -D /var/lib/postgresql/data \
       -o "-c listen_addresses='localhost'" \
       -w start
psql --command "CREATE USER docker WITH SUPERUSER PASSWORD '$password';"
postgres pg_ctl -D /var/lib/postgresql/data -m fast -w stop
exec $@

You can also have a look at the Dockerfile and entrypoint script of the official postgres image, from which I've borrowed most of the code in this answer.

A note on security

Storing secrets like passwords in environment variables (both build and run time) is not incredibly secure (unfortunately, to my knowledge, Docker does not really offer any better solution for this, right now). An interesting discussion on this topic can be found in this question.

Community
  • 1
  • 1
helmbert
  • 35,797
  • 13
  • 82
  • 95
  • Does that only work for build time though? I'm ideally looking for my user to specify it at startup. From the documentation '--build-arg=[] Set build-time variables'. – Andy Apr 08 '16 at 16:03
  • Ah, I've misread the question then. As you've used Dockerfile statements in your question, I assumed you were asking about setting the password at build time, not at run time. I'll update my answer. – helmbert Apr 08 '16 at 17:00
0

You could use environment variable in your Dockerfile and override the default value when you call docker run using -e or --env argument.

Also you will need to amend the init script to run psql command on startup referenced by the CMD instruction.

Daniel Stefaniuk
  • 5,264
  • 2
  • 17
  • 13