Member-only story
Getting started with Postgres in Docker
Creating a Postgres database in a Docker container for beginners
In this article we’ll spin up a Docker container with a pre-defined user and database. First we’ll create an .env file that’ll contain our database credentials. Then we’ll use this to spin up the container. In the last part I’ll show you how to connect to the database.
At the end of this article you’ll be able to connect to a pre-defined database that runs in a docker container. First we’ll set up some things for creating our database and then we’ll go through the steps that are required to run the container. Let’s code!
Setup
First we’ll create an environment file; a file that contains all of our confidential environment variables like our database credentials. We can “inject” all variables from this file into the Docker container upon running it (more information in this article).
Let’s first create our environment file that’ll contain our database credentials. We’ll call the file dbcredentials.env
and add the following content:
POSTGRES_HOST=my_db
POSTGRES_USER=mike
POSTGRES_PASSWORD=supersecretpassword
POSTGRES_DB=my_project_db
In the next part we’ll use Docker-Compose to spin up our container. If you want to read more about Docker or Docker-Compose check out this or this article.
Spinning up our container
With Docker Compose we specify how to spin up an image. In the parts below we check out the docker-compose.yml
files that spin up our database containers. They all have in common that they use the Postgres docker image.
You can set three environment variables spinning up Postgres’ Docker image: the username, password and database name. In the parts below we pass the variables in the env file in multiple ways. The implementation is a bit different but they yield exactly the same results. More information in this article.