What will be a software solution without a database system (or something similar)? It’s difficult to imagine.
Many times our software solutions requires a database system. However, I tend to avoid databases software installation, because these days we have docker
This post is to document my way of Docker and PostgreSQL for local development. However this concept perfectly works for other databases systems.
Hooray, here is the goal:
- Use Docker and PostgreSQL for local development. Avoid installing a database system.
- Use Docker Volumes for data persistent (this helped in WSL2).
- Use Docker Networks to link our apps with our databases system.
Docker commands:
The following commands helped out when I was on in Windows 10 (Home :D) using WSL2. According to info I found, $PWD *should* work, but it did not. Creating a Docker volume was the way it worked.
create a volume in docker:
1 | $ docker volume create --name volume_ttmo_demo_db |
create a network for our application
1 | $ docker network create network_ttmo_demo |
Launch a Postgres container:
1 | $ docker run --name container_ttmo_postgres -p 5432:5432 --network=network_ttmo_demo -v "volume_ttmo_demo_db:/var/lib/postgresql/data" -e POSTGRES_PASSWORD=super_secured_password -e POSTGRES_USER=user_ttmo_db -d postgres:13.2-alpine |
Launch a psql console:
1 | $ docker run -it --rm --network=network_ttmo_demo postgres:13.2-alpine psql -h localhost -U user_ttmo_db |
the previous fails because localhost is not valid in docker network:
1 2 3 4 5 6 | psql: error: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? could not connect to server: Address not available Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? |
it fails because locahost is not a valid name on the docker network, instead, as database server, we indicate the container name.
https://www.tutorialspoint.com/postgresql/postgresql_select_database.htm
Update parameters and re-execute psql console:
1 2 3 4 5 6 | $ docker run -it --rm --network=network_ttmo_demo postgres:13.2-alpine psql -h container_ttmo_postgres -U user_ttmo_db Password for user user_ttmo_db: psql (13.2) Type "help" for help. user_ttmo_db=# |
Now I can run psql commands:
1 2 3 4 5 6 7 | \?: display help \l: list all databases in server \q: quit the psql shell \c: connect to database \dt: list tables in database create database hello; -> this creates a database |
Cheers.