December 26, 2019

Bootstrap for a node and mongo environment with docker-compose

As a developer, I often need to quickly build a development environment for small projects and Docker is a very convenient way to have a stable one up and running in no time. Today I want to share my starting point when I have to build an app in node/express and mongoDB.

Disclaimer: This post is intended for development only, it is not suitable for devOps who are creating production environments.

I took the part of mongoDB from a Nya Garcia repository and I dockerized the node application as well to have an integrated environment to pull up with a simple docker-compose up

Here’s my docker-compose.yml:

version: "3.1"
services:
  api:
    container_name: nuovecodeApi
    image: node:11
    restart: always
    volumes:
      - ./src:/var/www/src
      - ./node_modules:/var/www/node_modules
      - ./package.json:/var/www/package.json
      - ./nodemon.json:/var/www/nodemon.json
      - ./tsconfig.json:/var/www/tsconfig.json
    build: .
    ports:
      - 8080:8080
    depends_on:
      - mongo
  mongo:
    container_name: mongoDB
    image: mongo:latest
    restart: always
    volumes:
      - ./nuovecodeData:/data/db
    environment:
      - MONGO_INITDB_DATABASE = nuovecodeDb
    ports:
      - 27017:27017

Now my api is accessible on localhost:8080 and my db on mongo:27017/nuovecodeDb

To avoid restarting the server every time you make a change you can use nodemon. A tool that checks for changes to application files and automatically restarts the server.

Here’s my default configuration:

{
  "watch": ["src"],
  "ext": "ts",
  "exec": "ts-node ./src/server.ts"
}

Why isn’t there a Dockerfile?

Note that there is no need to create a Dockerfile if you are using ready-made public images accessible from Docker Hub (in my case node and mongo)

No copyright / do whatever the hell you want with these contents
Built with Hugo and Kiss theme. Hosted on Netlify. Icons made by Ddara