Sometimes, you need a local database for testing/learning purposes. This post shows how to set up local databases of different types. The blog post will be updated as I learn more. The post assumes some familiarity with Docker and SQL but still has some in-depth explanations to make sure we understand the commands we’re running.
The following steps are based on the Docker blog post on how to use the PostgreSQL Docker official image.
Fist, run a PostgreSQL container:
docker run --name some-postgres -e POSTGRES_PASSWORD=mysecretpassword -d postgres
where:
run
- run a command in a new containername
- name of the containere
- environment variable
POSTGRES_PASSWORD
- password for the (default) user postgres
d
- run the container in the background (detached mode)Then, connect to the container:
docker exec -it some-postgres psql -U postgres
where:
exec
- execute a command in a running containerit
- interactive terminalsome-postgres
- name of the containerpsql
- command to run
U
- username
postgres
- default usernameWhen connected to the container, we can run SQL commands:
CREATE DATABASE mydb; -- create a database
\l -- list databases
\c mydb -- connect to a database
CREATE TABLE table (name VARCHAR(20), age INT); -- create a table
\dt -- list tables
INSERT INTO mydb (name, age) VALUES ('John', 30);
To disconnect from the database and container, simply press Ctrl/Cmd + D
.
To stop the postgres container:
docker stop some-postgres
To start it up again, run:
docker start some-postgres
and then, again, the docker exec
command from above.