Run Postgres in a Docker Container
If you want to run Postgres from a Docker container, but you have never tried your hands on Docker. Then this post is for you. In this post, I will explain how you can run Postgres or any other database from a docker image. So let’s start learning!
I am assuming that you have Docker installed on your machine. If not then Follow this link for installation instructions.
And if you are not comfortable with the terms like container and image, then check out this article. In that article, I have explained all these terms. So you don’t feel like working with alien technology.
Now have a look at this flow chart, this is a general representation of the steps included in running Postgres from a Docker image. And do not worry if you don’t understand it, we’ll go through it.
Now let’s start writing commands and also learn what those commands do.
- Open the terminal/command prompt and write the following command:
$ sudo docker run --name my-postgres-container -e POSTGRES_PASSWORD=postgres -p 5432:5432 -d postgres
What does this command do:
- Docker engine tries to run the image postgres from your system. If not found then docker-engine looks into the Docker Hub, pulls the image, and runs it for you. Then
run
command creates a container. So If you see the following in your terminal, It's fine.
Unable to find image 'postgres:latest' locally
- — name sets the name of your container. eg.
my-postgres-container
. - -e is used to set environment variables. eg.
POSTGRES_PASSWORD=postgres.
- We know that containers are isolated, so there is no way our container can connect to the network unless specified. For that, we map the port of our system to the port of the container. -p is used to specify the port mapping. eg
-p 5432:5432
- -d is used to run the container in the detached mode. The detached mode allows the container to run in the background.
- At last, we have specified the name of the Postgres image.
2. Now our container is up and running. You can connect to the Postgres from various GUI clients, eg PgAdmin, DBeaver, etc. If you want to do run Postgres from the command line then follow along with the next steps too.
3. Now let’s list the running containers with the following command.
$ sudo docker ps
- Here ps stands for process and we can give an additional option -a to view all containers(stopped and running).
$ sudo docker ps -a
4. Now we can enter the Postgres shell.
$ sudo docker exec -it my-postgres-container psql -U postgres
- exec stands for execution, it is used to run a command inside a running container.
- -it is used for interactive mode.
- We also have to specify the container. eg my-postgres-container.
psql -U postgres
is the command we want to run to start the Postgres shell.
And you are good to go!👍