Docker has made it easier for setting up a local developing environment. Developers longer have to install different database platforms, web servers, or caching servers manually anymore. In this blog post, you will learn how to install PostgreSQL using Docker Compose.
To use Docker and Docker-Compose you most have them installed if you already have them installed you can skip this selection. First, you need to install Docker you can find instructors on how to install Docker on your platform here. Second, you need to install Docker-Compose you can find instructors on how to install Docker-Compose on your platform here.
Inside the root folder of your project, create a file named docker-compose.yml and add this example to it:
# Create a service named db.
# Use the Docker Image postgres. This will pull the newest release.
# Give the container the name my_postgres. You can changes to something else.
# Setup the username, password, and database name. You can changes these values.
# Maps port 54320 (localhost) to port 5432 on the container. You can change the ports to fix your needs.
# Set a volume some that database is not lost after shutting down the container.
# I used the name postgres-data but you can changed it to something else.
To start the container, you only need to run one command. Make sure that you are inside of your projects root folder and run this command:
docker-compose up -d
This command reads the docker-compose.yml file, download the docker images that are needed, and set up your container based on the values in the file.
To connect to the PostgreSQL database run the following command:
psql -h localhost -p 54320 -U john -d mydb
After you run this command, you will be asked to enter a password.
To stop the container, you only need to run one command. Make sure that you are inside of your projects root folder and run this command:
This command will shutdown the PostgreSQL container.
In this blog, post you learned how to install PostgreSQL using Docker. You also learned how to start and stop the PostgreSQL container. You can find other blogs on Docker here.
Harrison Brock is a software engineer that focuses on Full Stack web development