Docker is cool! When using official Docker images, you can instantly have services up and running. A service that I use very often is PostgreSQL. It is a very powerful flavour of SQL, and thanks to the official Docker image you can get setup with it in seconds!
The Postgres image is on Docker Hub, where you can see different versions and thorough instructions on how to run the image.
Using barebones Docker images
docker run --name some-postgres-container -e POSTGRES_PASSWORD=mypassword -d postgres
Note: There are more environment variables you can use such as
Using Docker Compose
Docker Compose is an easy way to run multi-container applications, and all the fun things that come with that.
Copy the below into a
version: "2" services: db: image: postgres:alpine restart: always environment: - POSTGRES_USER=user - POSTGRES_PASSWORD=pass - POSTGRES_DB=mydb ports: - "5432:5432"
Then launch it using
docker-compose up --build
Note: This approach is not secure enough! Your database can basically be reached through
YOUR_IP:5432. For a more secure setup, read the below.
Docker Compose + Networks
If you're looking to access your Postgres DB from another container, it is important that you use a Docker network to do so. What this'll get you is access to the DB only from a container that is inside the network.
Here's your new
version: "2" services: db: image: postgres:alpine restart: always environment: - POSTGRES_USER=user - POSTGRES_PASSWORD=pass - POSTGRES_DB=mydb ports: - "5432" networks: - db-tier networks: db-tier: driver: bridge
Note: You should also add an app to this setup that'll try to access your Postgres DB. Once you do that, you can access your Postgres DB through that app through the url