Home > front end >  Docker Postgres data host volume mapping
Docker Postgres data host volume mapping

Time:09-27

I'm trying to docker-containerize PostgreSQL server and this container will have many other applications as well. The need is that, PostgreSQL server data should be mapped to the host volume so that when container is stopped, we won't lose the data. Also that, the next time when we start the container, the same directory can be mapped again and postgres can use the old data. Below is the DOCKERFILE. Note that I'm using ubuntu 22.04 on the host.

FROM ubuntu:22.04
ENV DEBIAN_FRONTEND noninteractive
RUN apt install -y postgresql
ENTRYPOINT ["tail", "-f", "/dev/null"]

Docker image is built using the command

docker build -t pg_test .

and the container is run using the command

docker run --name test -v /home/me/data:/var/lib/postgresql/14/main pg_test

'/home/me/data' is the host directory which is empty where I want to map the postgres server data. '/var/lib/postgresql/14/main' is the directory inside the docker container where the postgres is supposed to store the data.

Once the docker container starts, I enter the docker container using the command

docker exec -it test bash

and once I'm inside, I'm trying to start the PostgreSQL service. But PostgreSQL fails to start as there is no data in '/var/lib/postgresql/14/main' directory. I understand that since I have mapped an empty host directory to '/var/lib/postgresql/14/main' directory, postgres doesn't have the files required to start.

I understand that I'm doing it the wrong way, but I couldn't find a way around it. Can anyone please help me to do this the right way, if there is one?

Any help would be appreciable.

CodePudding user response:

You should use the postgres docker image, it will set up the db for you when you start the container, you can find instructions on https://hub.docker.com/_/postgres

If you must use a custom image, you will need to initialize the db yourself, usually by running initdb or whatever your system provides.

But really you should use the appropriate docker image, and if you need more services you start them in their own container and connect them to the postgres one

  • Related