Tutorial: Node, Express, Mongo with Docker

Recently I have been working on building MySpace From Scratch and sharing my journey here on Medium. At the very beginning of that series I went over setting up the environment for the project. I realized that a lot of people get overwhelmed when working with Docker so I wanted to write down a clear guide on how to get your Node project up and running with Docker in a manner of minutes.

Let’s Get Started — Installing Packages

Create a new folder for your new project and navigate to that folder in your terminal/command line. Run the following commands to install all the npm packages we need

npm install express
npm install mongoose
npm install nodemon
npm install cors

The Code

Create a new file called server.js
Here is what should go in that file:

Next create a src directory where the rest of your application will go. the server.js will act as a gateway into your application, and your app will be contained in the src directory. So your application will look like this:

/project
/src
... (routes, controllers, schemas, etc)
server.js

Docker Magic

First make sure you have installed docker on your machine. https://docs.docker.com/get-docker/

Then we need to create a Dockerfile. Create a new file named Dockerfile and add this:

Then we create a docker-compose.yml file, and add this:

And that’s all there is to it!

Running your Node App

From your project directory, run docker-compose up and everything will spin up and be working. As you make changes to the code the nodemon will automatically restart the server so you don’t have to run the docker compose again.

From here, create a front end client of some kind: a website or a mobile app. And make requests to http://localhost:3000 you can also navigate to that URL in the browser and see that your app is up and running.

Hopefully this short article has provided you a way to easily spin up new applications without worrying about setting up docker.

Thanks for reading my article, while you’re here consider following me on twitter!

Programmer — Writer. @andyhartnett12