Create a PostgreSQL Docker Container
Introduction to the creation of PostgreSQL and docker container
If you’re developing an application that interacts with a PostgreSQL database, there’s a good chance you may want to use a Docker container. Packaging an application and its dependencies in a container is an effective way to ensure that your app will work smoothly in any environment. In this article, we’ll show you how to use PostgreSQL and Docker together, providing step-by-step instructions on the installation and setup process.
Prerequisites to using Postgres
Although we’ll be running Postgres in a Docker container, we still need to have PostgreSQL and psql installed on our system.
Install Postgres and psql on Linux
Before you can use psql, you’ll need to install the postgresql-client-common
library. The following command shows how to install it on a Linux distribution using the APT repository:
1 | sudo apt install postgresql-client-common |
The following commands will install the PostgreSQL client:
1 2 | sudo apt-get install postgresql-client sudo apt-get install postgresql postgresql-contrib |
Install Postgres and psql on macOS
If you’re running macOS, you can use Homebrew’s brew
command to install Postgres and psql with the command shown below:
1 | brew install libpq |
Use these commands to install and start the PostgreSQL service with Homebrew:
1 2 | brew install postgres brew services start postgresql |
Install the Docker Engine
Make sure that you’ve also installed Docker because we’ll be using this to pull the Postgres image.
Install Docker on Windows
If you’re running Windows, login and download the installer here.
Install Docker on macOS
You can sign in and then download the DMG file for the interactive installer on macOS, or you can use Homebrew to install Docker.
Install ‘Docker’ on mac using Homebrew
Here’s how to use Homebrew’s brew
command to install the Docker CE:
1 | brew install docker |
You can then use the command docker --version
to display the version.
Install the Docker-Machine using Homebrew
The following Homebrew command can be used to install the Docker Machine on macOS:
1 | brew install docker-machine |
Before you can create a machine, you’ll need to install the virtual box. You can use this command to install it:
1 | brew cask install virtualbox |
Install ‘Docker CE’ on Ubuntu Linux
Now that we’ve covered the installation process on Windows and macOS, let’s talk about how to install Docker on an Ubuntu distribution of Linux. We’ll be using the APT-GET repository to handle the installation, so we’ll start the process by using the command sudo apt-get update
. This command will update the repository packages before installing.
First, we’ll install the dependency package for Docker:
1 | sudo apt-get -y install apt-transport-https ca-certificates curl software-properties-common |
Next, we’ll need to add the GPG key to the Docker Packages.
For a Debian-based distribution such as Linux Mint or Ubuntu, use the following command:
1 | curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add - |
Then add the .deb
` file for the Docker repository:
1 | sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(. /etc/os-release; echo "$UBUNTU_CODENAME") stable" |
Next, we’ll use the command cat /etc/apt/sources.list.d/additional-repositories.list
to view the newly-added line in the repositories file. After that, we’ll need to run sudo apt-get update
again to update the index of the package.
Finally, we’ll install both Docker CE and Docker Compose from the repository:
1 | sudo apt-get -y install docker-ce docker-compose |
At this point, it would be a good idea to check if Docker has been installed and the daemon has been started. Let’s run the command shown below:
1 | sudo systemctl status docker |
This command will display output stating that Docker is active:
If you’re using the YUM repository on a Red Hat Linux distribution such as CentOS or Fedora, you’ll need to perform the following steps:
1 2 3 | sudo yum install -y yum-utils \ device-mapper-persistent-data \ lvm2 |
Then you’ll need to grab the stable repository:
1 2 3 | sudo yum-config-manager \ --add-repo \ https://download.docker.com/linux/centos/docker-ce.repo |
Last but not least, you can install the Docker CE using the command shown below:
1 | sudo yum install docker-ce |
After you complete the installation, you can start it by typing this command:
1 | sudo systemctl start docker |
Use Docker ps to list containers
To show all running containers, we can use the docker ps
command. We use the docker -v
command to get the version of Docker that’s installed on the machine. When you run these commands, you might encounter a permissions error that says something like the following:
1 2 | Got permission denied while trying to connect to the Docker daemon socket.. |
If this occurs, use the following command to add your user, then log out and log in again:
1 | sudo usermod -a -G docker $USER |
Now try running docker ps
again, and it should list the following:
1 | CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES |
Pull the Postgres Docker image
We can use the docker pull
command to have the Docker engine download the official Docker image for Postgres from the registry. The following command will pull the image to the local Docker directory– typically, this location will be /var/lib/docker
:
1 | docker pull postgres |
Since we already installed everything we need for Docker, we can go ahead and create a Docker container that pulls the Postgres image:
A Docker image is made up of a series of read-only layers that are generated during the build of a Docker container. If you modify the files, Docker will just copy the layer where the changes were applied. When a Docker container is deleted, all of the changes made to the container will be lost. To persist this data, we’ll implement the concept of volumes in the Docker container.
Let’s look at the command used to create a volume:
1 | docker volume create pgdata |
To inspect the volume we just created, we use the following command:
1 | docker volume inspect pgdata |
This command should return output that looks like this:
1 2 3 4 5 6 7 8 9 10 11 | [ { "CreatedAt": "2019-11-05T16:12:44+08:00", "Driver": "local", "Labels": {}, "Mountpoint": "/var/lib/docker/volumes/pgdata/_data", "Name": "pgdata", "Options": {}, "Scope": "local" } ] |
Next, we’ll start our instance of Postgres and use the 5432:5432
part of the command to bind the default 5432 PostgreSQL port to our localhost. The following example illustrates how this is done:
1 2 3 4 5 6 | docker run -p 5432:5432 -d \ -e POSTGRES_PASSWORD=1234 \ -e POSTGRES_USER=postgres \ -e POSTGRES_DB=demo \ -v pgdata:/var/lib/postgresql/data \ postgres |
We’ll check that the container is running by using the docker ps
or docker container ls
commands. The returned results should look something like the following:
1 2 | CONTAINER ID IMAGE Now you can u COMMAND CREATED STATUS PORTS NAMES b2e72fa0444f postgres "docker-entrypoint.s…" 2 minutes ago Up 2 minutes 0.0.0.0:5432->5432/tcp silly_sinoussi |
There’s a lot going on in the command shown above. Let’s take a closer look at how it works:
The
-p 5432:5432
binds the port on localhost to the container. This means you’ll able to run applications outside of the Docker container and connect to the PostgreSQL server.The
-d
is used to enable the launcher of the container in the background.The
-e
sets an environment variable containing the value of the Docker container. It sets the password, user and the database. If these values are not provided, it will use the default value of “postgres”.The
-v
is used to mount ‘pgdata’ to the container path. This volume will persist even if the container is deleted.
Postgres Docker project directory
If you’d like to create a project folder with a bind-mounted volume for Postgres data at that project location, simply create a directory for the project and then change into it:
1 | mkdir postgres-docker; cd postgres-docker |
We’ll need to create a docker-compose.yml
config file to modify our container so that we can bind-mount a local directory for our Postgres databases and tables. The following command will create the YAML file using the Sublime editor:
1 | subl docker-compose.yml |
Set up the docker-compose file for the Postgres container
The following YAML script shows how you can set up the docker.compose.yml
file for your project:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | version: "3" services: # Service for the Postgres database db: # Pull the latest 'postgres' image image: "postgres" container_name: "postgres_docker" # Postgres environment parameters environment: - POSTGRES_USER = objectrocket - POSTGRES_PASSWORD = "sTrOnGpAsSwOrD" - POSTGRES_DB = some_database # Bind mount the default Postgres port ports: - "54321:5432" # Bind mount local volume for Postgres data volumes: - ./pg-data:/var/lib/postgresql/data |
NOTE: Be sure to change the 54321
port and the pg-data
bind-mounted directory to match your personal specifications.
Use docker-compose to start the container
After modifying your docker-compose file with the YAML data, save it and then run the following command inside of your project directory. This will have Docker create a container using the above specifications:
1 | docker-compose up |
If we use the ls
command (or dir
in Windows) in another terminal tab, we’ll see that the pd-data
folder was automatically created.
We can use the following commands to enter Postgres:
1 2 | sudo -u postgres -i psql |
Connect and run some queries in the psql
If you already have PostgreSQL installed on your machine, you can use the command shown below to connect:
1 | psql demo -h localhost -U postgres |
Otherwise, you can connect to the container using the Docker exec
:
1 | docker exec -it b2e72fa0444f psql -U postgres demo |
NOTE: Remember to replace b2e72fa0444f
with your container ID. If you’re not sure of the ID, use the docker ps
command to have the Docker engine return a list of all of your containers.
Conclusion to PostgreSQL and Docker
If you’re interested in developing an application that can be packaged to work seamlessly in nearly any environment, a Docker container may be the right tool for the job. In this tutorial, we explained how to use PostgreSQL in a Docker container, walking through each step involved in the installation and configuration process. With these instructions to guide you, you’ll be able to work with PostgreSQL and Docker in your own development efforts.
Pilot the ObjectRocket Platform Free!
Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.
Get Started