Skip to content

Dockerize everything

Fabrice Hafashimana edited this page Aug 9, 2022 · 2 revisions

Not everything as the title suggest...

Introduction

One of the technology we are using is Docker, but there is more to docker than just deploying a container. From allowing you to run multiple containers to specifically setting ports for service. This WIKI will help you setup the project and start coding with local databases that are running as docker containers.

Advantages

Locally hosted database are very fast compared to using online hosted (Latency and the usual request/response cycle), but also in development, they are very reliable. You can just spin up a database and delete the database anytime. PROs:

  • Ability to spin up more than 3 containers running Mongo (Dev, Test, Production)
  • Specific settings for each container
  • Ability to exclusively setup the restart behavior
  • Use low memory usage

CONs:

  • I have no idea on this part (Just had to add this one)

Code

Not code but commands. We are going to setup two containers that we will be using for development and testing. I will be explaining some parts but be sure to check if the following are there.

  • Docker installed and running
  • A stable internet

Development Database

All commands will be the same here

// basic docker container that you can spin up and use default setup
docker run --name devpulse_db_dev -p 27000:27017 -d mongo:latest
// the setup link will be mongodb://localhost:27000
// you can also use run another instance of docker on different port
docker run --name devpulse_db_test -p 28000:27017 -d mongo:latest

The issue with the above setup is that you will need to start the containers each time you restart your machine. This can get tiresome very fast, so let us solve that issue using the restart flag of docker.

// updated commands
docker run --name devpulse_db_dev -p 27000:27017 --restart always -d mongo:latest
// this will ensure that the container will always start after the docker deamon has started (After restart of system or otherwise)
// to update our previous containers without running a new one
docker update --restart always devpulse_db_test
docker update --restart always devpulse_db_dev

Conclusion

Docker is a fantastic tool and you can play with it. Try creating a docker container for production environment where you will set a custom username and password to be used in authentication. Don't peak on the answer before you try it.

Answer

docker run --name devpulse_db_pro -p 29000:27017 -e MONGO_INITDB_ROOT_USERNAME=username -e MONGO_INITDB_ROOT_PASSWORD=password --restart always -d mongo
// use this link to connect
// mongodb://username:password@localhost:27000

Notice that we used different port. Instead of using 27017 which is a default port, we used a more readable port. This allow us to avoid port conflicts if we already have mongo running on our system

Clone this wiki locally