Running Postgres in Docker

This is a very brief post showing how to run Postgres in a Docker container. I am writing this because the instructions on the Postgres Docker page don’t actually show how to expose the database port so you can connect to the database from the host computer.

Here is all you need to do to run Postgres in a Docker container -

docker pull postgres
docker run -it -p 5432:5432 -e POSTGRES_PASSWORD=postgres postgres

This will pull the latest Docker image and run the container, setting the password to postgres and mapping port 5432 on the container to port 5432 on the host, so you can connect to the database from your host machine. By default, the username is postgres.

I am leaving this as an interactive container so you can see the output from the database. If you want to run it in the background, just add the -d flag to the docker run command.

I don’t know why, but the Docker page as of this writing doesn’t show the -p 5432:5432 part. I hope this helps someone.

For C# this will give you a connection string like this -

Host=localhost;Port=5432;Database=somedatabase;Username=postgres;Password=postgres

The above command won’t persist the data in the database. If you want to do that, you can add a volume to the command like this -

docker run -it --name mypostgres -p 5432:5432 -e POSTGRES_PASSWORD=postgres -e PGDATA=/var/lib/postgresql/data/pgdata -v /custom/mount:/var/lib/postgresql/data postgres

If you stop the container and want to restart it, use -

docker start -i mypostgres

comments powered by Disqus

Related