When it comes to provisioning a local dev environment, you have at least 4 choices. One, you can offload all the heavy lifting to a 3rd-party service. For example, you could use Atlas or mLab for MongoDB, and Redis Labs for Redis. Just copy-paste the connection string, and you’re ready to go. Otherwise, you could also install mongodb-org and redis-server locally on your machine. This is the most intuitive, yet also most intrusive approach as it directly uses your OS to run both processes.

Another option is to install MongoDB and Redis in a VM such as Vagrant, which would eat up substantial resources to run a full-blown Linux OS alongside your host OS. This is probably an overkill when used for development. Lastly, you can provision both databases with Docker and (optionally) Docker Compose. We’ll go with the last option in this tutorial.

First, make sure to install docker and docker-compose on your machine. If you’re new to Docker, it will take some time to get used to, but once you’ve picked on a few simple commands, you can easily spin up light-weight containers for your everyday development. Docker Compose is useful when you need to manage multiple containers under a stack. Just keep in mind that it only works on a single host, and as such is only suited for local development. Don’t get too hung up on it, as you’ll probably use Kubernetes or Swarm in production anyway.

Sadly, MongoDB image doesn’t create an admin user for the initial database, although it’s a open issue on GitHub. To do so, you can map a shell script to the MongoDB entrypoint directory. This could be a JS file as well, except then you won’t have access to environment variables. The shell script needs to authenticate with MongoDB, create an admin user, and grant them write permissions on the initial database.

One issue that you will run into on Linux (either locally during development or in production after deployment) is directory ownership of the data volume. When you map the data directory from a MongoDB container to a local file-system directory, its ownership changes recursively to an elevated user, such as root. You can find this problem described in these GitHub issues.

To fix this on Linux, before running any docker-compose command (not only up, but also stop, down, etc.), you need to (1) explicitly export UID in the current shell, and (2) make the volume directory (with -p if it already exists). This way data directory is owned by the currently logged-in user (i.e. you) and not an elevated user (i.e. root). Otherwise, its ownership will silently change to root, and you may run into critical errors when re-booting the container stack.

#node.js #docker #linux #docker compose

Authentication in Node.js - #3 Docker Compose for Development
1.20 GEEK