PostgreSQL in a docker container
You presumably want to make a database for your little project. I presumably want to tell how. Read on.
Creating and running the container
docker run -p 5432:5432 -d \
-e POSTGRES_PASSWORD=postgres \
-e POSTGRES_USER=postgres \
-e POSTGRES_DB=database-example \
-v pgdata:/var/lib/postgresql/data \
- -p 5432:5432 — port 5432 (left) is the port on the host machine that will be used to access the container. It will map to port 5432 (right) in the container.
- -d — discrete. The container will run but will not print its log in the terminal. It will run discretely.
- -e — Environmental variables. These variables will be available within the container. We are declaring the user, password, and name of the database.
- -v pgdata:/var/lib/postgresql/data — we are creating a named volume called pgdata and mounting it at that location inside the container
- postgres — name of the image we will be using
Connecting to the container
docker exec -it <container-id> psql -U postgres database-example
- exec — Execute this command inside the container
- -it — Effectively makes it appear as a terminal session, so you can keep typing psql queries
- <container-id> — find by executing the command
docker container lsand copying the id
- psql -U postgres database-example — a postgres command, as you may already be familiar with it, to enter the “database-example” database as the user “postgres”
You can connect to the database using the details selected above. Perhaps you may want to furnish an environments file with these little goodies:
Directly copied from a tutorial by the significantly more capable Ben Awad