3 min to read
Postgres in Docker
Docker makes it easy to spin up a Postgre Database on your server or local machine. With the following command you can start your PostgreSQL Docker container
# Name, password and local port(54320) can be changed, based on your preference
# We are using postgres alphine image here.
docker run --name mypostgres -e POSTGRES_PASSWORD=password -d -p 54320:5432 postgres:alpine
# To keep the data persistant, volume reference can be added
# Data will be saved under "data" directory in the current path
docker run --name mypostgres -v "$PWD"/data:/var/lib/postgresql/data -e POSTGRES_PASSWORD=password -d -p 54320:5432 postgres:alpine
Accessing the container can be done in multiple ways
- To login interactively to postgres container
docker exec -it mypostgres psql -U postgres
- Connect using psql commands
psql --host localhost --port 54320 --user postgres
- Connect via pgAdmin
To create container more conveniently we can use a docker-compose.yml file instead of running Docker CLI commands.
version: "3"
services:
# Create a service named postgresdb.
postgresdb:
# Use the Docker Image postgres alpine. This will pull the newest release.
image: postgres:alpine
# Give a name for the container.
container_name: "mypostgres"
# Setup the username, password, and database name. You can changes these values.
environment:
POSTGRES_USER: 'postgres'
POSTGRES_PASSWORD: 'pgpass'
POSTGRES_DB: 'postgres'
# Maps port 54320 (localhost) to port 5432 on the container. You can change the ports to fix your needs.
ports:
- "54320:5432"
# Set a volume to keep the data persistant (data is not lost after shutting down the container).
# You can use different directory name other than "db-data" if you want
volumes:
- ./db-data:/var/lib/postgresql/data
Once docker-compose.yml is created.Open a terminal in the same directory and use following commands to start and stop the container.
# Start the container
docker-compose up -d
# Stop the container
docker-compose down
pgAdmin service can be added to the docker-compose file to make pgAdmin run as a docker container alongside the postgresDB container. Complete docker-compose file can be found here
# Create a service for pgadmin.
pgadmin:
# Use pgadmin4 Docker image, https://hub.docker.com/r/dpage/pgadmin4/
image: dpage/pgadmin4
# Expose the web UI on localhost port 8080
ports:
- '8080:80'
# Link this container to the "mypostgres" container created above with hostname 'postgres'
external_links:
- mypostgres:postgres
# Login details for pgadmin can be set as per your preference
environment:
PGADMIN_DEFAULT_EMAIL: 'admin@example.com'
PGADMIN_DEFAULT_PASSWORD: 'admin'
Next time when you run docker compose, pgAdmin console can be accessed via localhost:8080 in the browser.
To connect to the postgresDB, click on “add new server”. Then specify a name for connection under General. Under connections put the details for the postgres docker container and click save.
New connection can be seen on left hand sidebar
Comments