Creating a managed PostgreSQL service
Prerequisites
- A virtual private server running Ubuntu Linux. I recommend getting one from Digital Ocean.
- An understanding of Docker
Initial Server Setup with Ubuntu
When you first create a new Ubuntu 20.04 server, you should perform some important configuration steps as part of the initial setup. These steps will enhance the security and usability of your server, providing a solid foundation for subsequent actions.
We won’t go over that in this article. However, you can use this in-depth tutorial provided by Digital Ocean.
Setting up Docker
As we’ll be using Docker and Docker Compose for managing our PostgreSQL container, we will need to set up Docker next.
We can easily install Docker on our machine by running
curl -fsSL [https://get.docker.com](https://get.docker.com/) -o [get-docker.sh](http://get-docker.sh/) sh [get-docker.sh](http://get-docker.sh/)
You can then run
docker -v docker compose version
This should output the Docker version, the build, and the Docker Compose version
Setting up a Docker Compose File
We’d need to run a Docker compose file on our virtual machine. We can create it directly and edit it with an inbuilt text editor like vim or nano, however, that will get messy quickly
We can instead set up a Git repository, you can set this up on whatever account you have, and clone that repository to our VPS.
In our repo, we can create a docker-compose.yaml file and insert the following code into it
services:
postgres:
image: postgres
container_name: postgres-db
restart: unless-stopped
environment:
POSTGRES_USER: ${POSTGRES_USER}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
POSTGRES_DB: ${POSTGRES_DB}
ports:
- "${POSTGRES_PORT}:5432"
volumes:
- pgdata:/var/lib/postgresql/data
volumes:
pgdata:
name: postgres_data
Create a .env file
This file should sit in the same directory as your docker-compose.yaml
POSTGRES_USER=myuser
POSTGRES_PASSWORD=supersecurepassword
POSTGRES_DB=mydatabase
POSTGRES_PORT=5432
You can replace the values with whatever you want.
We can then run:
docker compose up -d
This will run a PostgreSQL instance using whatever environment variables you set, alternatively, you can run
docker ps to see your running PostgreSQL container