Akashii
Akashii

Reputation: 2281

Wait service postgres start dockerfile

I'm using docker file to build ubuntu image have install postgresql. But I can't wait for service postgres status OK

FROM ubuntu:18.04
....
RUN apt-get update && apt-get install -y postgresql-11
RUN service postgresql start
RUN su postgres
RUN psql
RUN CREATE USER kong; CREATE DATABASE kong OWNER kong;
RUN \q
RUN exit

Everything seem okay, but RUN su postgres will throw error because service postgresql not yet started after RUN service postgresql start. How can I do that?

Upvotes: 0

Views: 1231

Answers (1)

Adiii
Adiii

Reputation: 60074

First thing, each RUN command in Dockerfile run in a separate shell and RUN command should be used for installation or configuration not for starting the process. The process should be started at CMD or entrypoint.

RUN vs CMD

Better to use offical postgress docker image.

docker run --name some-postgres -e POSTGRES_PASSWORD=mysecretpassword -d postgres

The default postgres user and database are created in the entrypoint with initdb. or you can build your image based on postgress.

FROM postgres:11
ENV POSTGRES_USER=kong
ENV POSTGRES_PASSWORD=example
COPY seed.sql /docker-entrypoint-initdb.d/seed.sql

This will create an image with user, password and also the entrypoint will insert seed data as well when container started.

POSTGRES_USER

This optional environment variable is used in conjunction with POSTGRES_PASSWORD to set a user and its password. This variable will create the specified user with superuser power and a database with the same name. If it is not specified, then the default user of postgres will be used.

Some advantage with offical docker image

  • Create DB from ENV
  • Create DB user from ENV
  • Start container with seed data
  • Will wait for postgres to be up and running

All you need

# Use postgres/example user/password credentials
version: '3.1'

services:

  db:
    image: postgres
    restart: always
    environment:
      POSTGRES_PASSWORD: example

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.

Upvotes: 2

Related Questions