In this blog I will show step by step how to setup PostgreSQL in Docker on your local machine.
-
Pull the latest PostgreSQL image:
docker pull postgres:latestor specify a specific version:
docker pull postgres:16 -
Create a Docker volume to preserve data:
docker volume create postgres-data -
Run the PostgreSQL container:
docker run --name my-postgres \ # Names your container
-e POSTGRES_PASSWORD=mypassword \ # Set the superuser password -e POSTGRES_DB=mydatabase \ # Creates an initial database -p 0.0.0.0:5432:5432 \ # Maps port so that your local machine can connect to the database locally -v postgres-data:/var/lib/postgresql/data \ # Mounts the volume for data persistence -d postgres:latest # Runs container in detached mode
4. Verify the container is running:
`docker ps`
5. Connect the PostgreSQL:
`docker exec -it my-postgres psql -U postgres -d mydatabase`