Sep 22 2022

Node.js + Docker Development

A page about how to Dockerize a Node.js application exists on the Node.js site. There is a corresponding page about using containers for development on Docker’s site. Those guides are fine in theory. In practice, it can be a little tricky to use a dev server like Vite or Astro on your local machine with Docker Desktop. For example, you may find that HMR appears to work when you save a file, and yet the browser window doesn’t refresh automatically.

Partly to record how to do it for myself, I created a demo repo on GitHub for Astro + Docker. Here’s what’s most important. The Dockerfile looks like this:

FROM node:18-alpine
COPY package*.json .
RUN npm ci --audit=false --fund=false
CMD ["npm", "start"]

…and the docker-compose.yml file looks like this:

    build: .
      - "3000:3000"
      - "./:/app"
      - "/app/.tscache"
      - "/app/dist"
      - "/app/node_modules"

Notice that the usual COPY statement to copy the source files appears to be missing. That is intentional. When docker compose runs, our files are mounted as a volume from the local file system and shared with Docker. Thus the files we change in the editor are the same as what the Node.js process running inside the container is monitoring, not a copy. Voilà.

Even so, I prefer to shut Docker down and run my code directly Node.js on my local machine whenever possible.