2021/11/12

docker development container for node

Using a docker container for node.js development is a good idea for a few reasons. It easily allows the development environment to be shared with others and provides some amount of separation from the host system. While far from being locked-down, running npm install inside of the container can help prevent install scripts from exploiting the host machine. Given how common these types of vulnerabilities have become, this is something that any npm user should be aware of.

The setup is simple, consisting of a Dockerfile, docker-compose.yml, and a single package.json script. This will let you spin up the container and get a shell inside of it to install packages and run commands. It can be further modified to automatically run a command and be used for deployment, but I'll leave that as an exercise for the reader.

Dockerfile

FROM node:latest
WORKDIR /app/
COPY package.json .
RUN npm install
COPY . .

docker-compose.yml

version: '3.8'
services:
  project:
    build:
      context: .
    command: bash
    volumes:
      - .:/app/
      - /app/node_modules

package.json

You can use an existing package.json, or create one for yourself by running npm init.

...
  "scripts": {
    ...
    "docker:shell": "docker-compose run project",
    ...
  },
...

Once that's setup, run docker-compose up --build -d to start the container and then npm run docker:shell to get a shell inside of it. From their npm install and everything is up and running! Get out of the container by running exit inside of it. Use docker-compose down -v outside of the container to completely tear it down if you want a clean start.

If you plan to run a server, you need to be sure to expose and use the proper ports. Thanks to the container being mounted in the project directory, you can use your favorite editor to create and modify files on your host system while running them on the container.

This is far from perfect, but is a step in the right direction and should provide some value to the developer and maybe some small amount of security.