What’s the quickest way to spin up a local development database? Using Docker, of course!
With Docker you can literally have a database up and running in moments. It’s very convenient indeed.
PostgreSQL
Let’s launch a PostgreSQL database.
Manually
Pull and run the postgres
Docker image.
docker run -d --name postgres --rm -p 5432:5432 postgres
We’re mapping port 5432 on the container to port 5432 on the host.
You can now connect to the database using user postgres
and leaving the password empty. The default database is postgres
. You can immediately start creating tables and adding data.
To stop the server:
docker stop postgres
Compose
To make this easier to repeat, set up Docker Compose by creating a docker-compose.yml
file with the following contents:
version: '3'
services:
postgres:
container_name: 'postgres'
image: 'postgres:9.6.16'
ports:
- '127.0.0.1:5432:5432'
volumes:
- 'data_postgres:/var/lib/postgresql/data/'
volumes:
data_postgres:
For stability we’ve selected a specific version of PostgreSQL (9.6.16). You are free to choose another version or just omit the version tag, in which case you’ll get the most recent.
docker-compose up -d
When you’re done, just bring it down.
docker-compose down
MySQL
Now let’s try a MySQL database.
Manually
Pull and run the mysql
Docker image.
docker run --name mysql --rm -e MYSQL_ALLOW_EMPTY_PASSWORD=1 -p 3306:3306 mysql
We’re mapping port 3306 on the container to port 3306 on the host.
You can now connect to the database using user root
and leaving the password empty. You’ll need to create a database before you can start adding tables and data.
Compose
Again, it makes sense to handle this setup with Docker Compose.
version: '3'
services:
mysql:
container_name: 'mysql'
image: 'mysql:8.0.21'
ports:
- '127.0.0.1:3306:3306'
environment:
MYSQL_ALLOW_EMPTY_PASSWORD: 1
volumes:
- 'data_mysql:/var/lib/mysql'
volumes:
data_mysql:
Conclusion
Docker is a phenomenal tool for setting up this sort of infrastructure in a flexible and portable way.