Run Postgresql
Perhaps the easiest way to run PostgreSQL is to do so in Docker.
Make Sure Docker is Running
We’ve made sure Docker is installed, now let’s make sure it’s running. We can do this by opening a terminal or command prompt and running the following:
docker psIf we see an empty list of running containers then we’re good to go. Otherwise you may need to launch Docker, which you can often do from start menus and application directories.
Create a Docker Compose File
Next we create a Docker compose file which runs PostgreSQL.
We use Docker Compose rather than Docker directly, as it allows us to specify an environment of one or more containers, all in yaml.
Not only is being able to manage our entire environment in one configuration file easier than using disparate Docker commands to set things up, you can check it into source control as well so it’s replicable across different developer’s machines.
We’ll create a file named docker-compose.yml in the root of our project with the following contents:
services:
# Our PostgreSQL database
db:
# The Docker image of postgres -- we're using the latest.
image: postgres:latest
# The ports to expose to the host container
# 5432 is the default PostgreSQL port
ports:
- "5432:5432"
# If we accidentally kill the running container, Docker Compose
# will restart it.
restart: always
# The PostgreSQL Docker container uses environment variables to
# read configuration, here we set the password.
# ⚠️ - Do no store plaintext passwords in source control. We
# do so here as this is a builder.
environment:
POSTGRES_PASSWORD: changemeinprod!Understanding the Docker Compose File
Looking over the docker-compose.yml file, we can see a service, which specifies an instance of the docker image postgres:latest should run, exposing port 5432 (the default PostgreSQL port) for us to connect.
We can also see an environment variable POSTGRES_PASSWORD specified. This is how we tell the Docker container the password for the postgres user.
Note that we’re not specifying any Docker volumes here – this means that if we restart our Docker environment then we will lose data in the database. Obviously not desirable in a production environment, but quite handy in a development environment.
Running Docker Compose
Now we can run our Docker Compose environment.
To do this, we’ll open a terminal or command prompt and navigate to the directory where the docker-compose.yml file is located.
Then we run:
docker-compose upAt this point Docker will download the postgres:latest docker image, if you don’t have it locally, and then run it ready to connect on port 5432, ready to connect to from our Task app backend.
Summary
-
Docker and Docker Compose are used to run PostgreSQL
-
Running
docker-compose uplaunches the PostgreSQL container -
The database is accessible on localhost:5432
-
The container can be checked using
docker pscommand