One Liners for Quickly Setting Up a Database for your Project using Docker
Ever needed to quickly set up a database to connect to in development? Typically you need to download and install the database of your choice (such as MySQL, PostgreSQL, etc.) on your local environment but there is an easier way to go about this. In this article, I will show you how you can very conveniently spin up any database locally using a single Docker command!
Install Docker
The first step is to make sure you have Docker installed for your platform and that it is up and running. You can check this by running:
docker info
It should print a bunch of information about Docker if it is running on your machine.
Run a one-liner
Now, all we need to do is paste one of the following commands into the terminal. I’ve provided the most common flavors of databases for your convenience:
// PostgreSQL
docker run --rm --name postgres-db -p 5432:5432 -e POSTGRES_PASSWORD=mypassword -d postgres// MySQL
docker run --rm --name mysql-db -p 3306:3306 -e MYSQL_ROOT_PASSWORD=mypassword -d mysql// MongoDB
docker run --rm --name mongo-db -p 27017:27017 -e MONGO_INITDB_ROOT_PASSWORD=mypassword -e MONGO_INITDB_ROOT_USERNAME=admin -d mongo
If it's the first time running each command, Docker will automatically download the image it needs.
The commands can be broken down as follows:
- We’re using the Docker
run
command to run each image with Docker. - The
--rm
command removes the container if exited. - We give the container a name using the
--name
flag. - We forward the default port of each database using the
--port
flag. - The
-e
flag sets the environment variables for the root password and user as the database starts up. - The last part of the command is the actual image and with the
-d
flag the process will be ‘detached’, meaning it will run in the background.
Now, if you run the docker ps
command you should see your database running in Docker:
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMESbe22ee7d4219 mongo "docker-entrypoint.s…" 12minutes ago Up 12 minutes 0.0.0.0:27017->27017/tcp mongo-db...
As long as you have the correct CLI tools installed you can connect to your database in the terminal:
// Connect to PostgreSQL
psql --host=0.0.0.0 --user postgres// Connect to MySQL
mysql --host=0.0.0.0 -u root --password// Connect to MongoDB
mongo -u admin -p mypassword
Conclusion
There you have it! Next time you need to run a database in development, pop one of these one-liners into the terminal and you’ll be up and running within seconds. If you have any suggestions of additional database one-liners or any improvements to the ones above, leave a comment and I’ll add it to the list!