Learning how to run PostgreSQL in a Docker Container

            # Learning how to run Postgres in a Docker container

The steps that I took

  1. Find a suitable docker image on docker hub. I picked a recent (10.5) Alpine (lightweight version).
$ docker pull postgres:10.5-alpine
10.5-alpine: Pulling from library/postgres
Digest: sha256:295a08ddd9efa1612c46033f0b96c3976f80f49c7ce29e05916b0af557806117
Status: Image is up to date for postgres:10.5-alpine

$ docker image ls                                                                                                                                                                                                          
REPOSITORY                     TAG                 IMAGE ID            CREATED             SIZE
postgres                       10.5-alpine         294f651dec48        5 weeks ago         71.6MB
  1. Then docker image ps will confirm that the image is available.
  2. Now run the image (i.e. build an instance of that image henceforth known as container). In addition, we will name the image, map the port and pass in an environment variable with the password for log-on.
$ docker run --name psql-foo -p 5432:5432 -e POSTGRES_PASSWORD=FOOBAR -d postgres:10.5-alpine

You could now connect to the database from an application (e.g. I used TablePlus or use a locally installed version of pgAdmin4.

Alternatively, you could run both the database and pgAdmin4 together in separate but networked containers.

version: '3'

    image: postgres:10.5-alpine
    hostname: postgres
      - "6543:5432"
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: postgres
      - postgres-data:/var/lib/postgresql/data
    restart: unless-stopped

    image: dpage/pgadmin4
      - db
      - "5555:80"
      PGADMIN_DEFAULT_EMAIL: pgadmin4@pgadmin.org
    restart: unless-stopped


To connect, you now need to navigate to http://localhost:5555 on your local machine, enter pgadmin4@pgadmin.org as the username and admin as the password to log-on, then follow the link to add a server. Then configure the server settings as below (in particular, note that the host is not localhost but the name of the host you set up in the docker-compose file.

Screenshot of Safari  20 10 2018 08 11 50

You can also use the psql interactive terminal client via docker exec. First use docker ps to identify the container that is running PostgreSQL, then launch via bash using docker exec.

$ docker ps
CONTAINER ID        IMAGE                  COMMAND                  CREATED             STATUS              PORTS                           NAMES
e936db289c39        dpage/pgadmin4         "/entrypoint.sh"         15 hours ago        Up 15 hours         443/tcp,>80/tcp   psql_admin_1
98c037358b46        postgres:10.5-alpine   "docker-entrypoint.s…"   15 hours ago        Up 15 hours>5432/tcp          psql_db_1
$ docker exec -it 98c /usr/local/bin/psql -h db -U postgres
Password for user postgres:
psql (10.5)
Type "help" for help.