Zero-Downtime Deployments for Node Apps With Docker Compose · Part 3 of 11 in the series
Part 3: The App in a Container
Pack the guestbook into a Docker image that checks its own health, run it beside its database with Docker Compose, and watch it shut down gracefully when the container is stopped.
Zero-Downtime Deployments for Node Apps With Docker ComposePart 3 of 11
On this page
Quest objectives
- Know what an image and a container are
- Write a Dockerfile for a Node.js app, line by line
- Let Docker ask the health check by itself
- Run the app and its database together with Docker Compose
- See the graceful shutdown work inside a container
- Build the commit ID into the image as its version
So far the guestbook runs on your computer because your computer happens to have the right Node.js and the right packages. A server would need the same, set up by hand and kept in step forever. Docker solves that with two things:
An image is a package that holds your app and everything it needs: Node.js, the installed packages, your code. It is built once and never changes.
A container is a running copy of an image. You can start as many as you like from the same image, and each one behaves the same, on your computer and on any server.
This is what makes the rest of the series possible. The server will never see your source code and will never run npm install. It only fetches finished images and starts containers from them. And "the new version beside the old one" is nothing more than two containers from two images.
The Dockerfile
An image is built from a recipe called Dockerfile. Create it in the project folder, with exactly this name:
FROM node:26-alpine
WORKDIR /app
ENV NODE_ENV=production
# The dependencies first: this layer is reused as long as they do not change.
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
COPY src ./src
COPY migrations ./migrations
# Which commit this image was built from. The pipeline passes it in.
ARG APP_VERSION=dev
ENV APP_VERSION=$APP_VERSION
USER node
EXPOSE 3000
HEALTHCHECK --interval=5s --timeout=3s --start-period=20s --start-interval=1s \
CMD wget --quiet --spider http://127.0.0.1:3000/health || exit 1
CMD ["node", "src/server.js"]From top to bottom:
FROMnames the image to start from: one that already has Node.js 26, on Alpine, a very small Linux.WORKDIRis the folder inside the image where everything else happens.NODE_ENV=productiontells Node.js and its packages that this is the real thing, not development.The first
COPYtakes only the two package files, andRUN npm ci --omit=devinstalls exactly the versions noted inpackage-lock.json, without packages that are only needed for development. Why not copy everything at once? Docker remembers the result of every line and reuses it as long as nothing that went into it has changed. Your code changes with every commit, the packages rarely. In this order, a new build skips the installing and takes seconds.The next two
COPYlines add your code and the migrations.ARGis a value that can be passed in when the image is built, andENVkeeps it as the environment variableAPP_VERSION. That is the variable the footer of the page reads. If nothing is passed in, it is dev.USER nodemakes the app run as a normal user callednode, which the base image brings along, and not as the administrator.EXPOSEis a note for people: this app listens on port 3000. It opens nothing by itself.CMDis the command a container runs when it starts.
That leaves HEALTHCHECK, the line this series depends on. With it, Docker itself asks the address from part 2. Every five seconds it runs the command behind CMD inside the container: wget requests /health, and --spider means it only asks and saves nothing. If the answer is not a 200, the command fails. After three failures in a row, Docker marks the container as unhealthy.
An app needs a moment to start, and the two start options are for that moment. During the first twenty seconds, a failed check does not count (--start-period), and Docker asks every second instead of every five (--start-interval). So a container that is ready after one second is known to be healthy after one second. In part 7, the deploy script waits for exactly this word, healthy, before it sends visitors to a new container.
Not everything in your folder belongs in the image. Create .dockerignore:
node_modules
.git
.env
deployDocker does not even look at what is listed here. node_modules stays out because the image installs its own packages, .git because the history is not needed to run the app, and .env because settings and passwords have no place in an image that is passed around. deploy is a folder you will create in part 6, for the files of the server.
Run it with Compose
Your compose.yml describes the database. Now it gets a second service, the app. Replace the file with this:
services:
web:
build: .
ports:
- '3000:3000'
environment:
DATABASE_URL: postgres://guestbook:guestbook@db:5432/guestbook
depends_on:
db:
condition: service_healthy
db:
image: postgres:18-alpine
ports:
- '5432:5432'
environment:
POSTGRES_USER: guestbook
POSTGRES_PASSWORD: guestbook
POSTGRES_DB: guestbook
volumes:
- db-data:/var/lib/postgresql
healthcheck:
test: ['CMD-SHELL', 'pg_isready -U guestbook']
interval: 5s
timeout: 3s
retries: 10
volumes:
db-data:The service db is unchanged. The service web is new:
build: .says: there is no finished image for this one, build it from the Dockerfile in this folder.portsmakes the app reachable from your computer on port 3000.DATABASE_URLis the address of the database again, with one difference from your.env: the computer is calleddb, notlocalhost. Inside a container,localhostis the container itself. Compose connects its services in a network of their own, in which each one is reachable under its name.depends_onwithservice_healthymakes Compose start the app only when the database reports that it is ready. That is what thehealthcheckof the database was for.
If npm run dev is still running, stop it with Ctrl+C: it occupies the port the container wants. Then build and start:
$ docker compose up --detach --build$ docker compose ps --format 'table {{.Name}}\t{{.Image}}\t{{.Status}}'NAME IMAGE STATUSguestbook-db-1 postgres:18-alpine Up 4 minutes (healthy)guestbook-web-1 guestbook-web Up 8 seconds (healthy)$ curl http://localhost:3000/health{"status":"ok","version":"dev"}
The first build takes a minute, because Docker fetches the base image and installs the packages. The list then shows both containers, and beside the app the word that matters: (healthy). Nobody typed a command for that. Docker asked the health check by itself, and the app answered. Open localhost:3000: it is the same guestbook with the same entries, because they live in the database's volume.
Stop it kindly
Now the second question from part 2. Stop the app's container and look at what it wrote:
$ docker compose stop web$ docker compose logs webweb-1 | Guestbook listening on port 3000web-1 | SIGTERM received, finishing open requestsweb-1 | All done, bye
There are the two lines again. Docker sent SIGTERM, the app finished and left by itself, well within the ten seconds Docker allows. An app without the handler would be cut off in the middle of whatever it was doing.
The image holds more than the app itself: the migrations and their script are in it too. A container can be started with another command than the one in the Dockerfile:
$ docker compose run --rm web node src/migrate.jsDatabase is up to date$ docker compose up --detach
docker compose run starts a container from the service's image for one task, here the migration script, and --rm removes it afterwards. There was nothing to do, because your database is up to date. This is exactly how the server will update its database before every deploy: with the new image, before the new version starts. The second command starts the app again.
A version in the image
One thing is left: the version. Git gives every commit an ID, and git rev-parse HEAD prints the one of your latest commit. Pass it in when you build:
$ docker build --build-arg APP_VERSION=$(git rev-parse HEAD) --tag guestbook-test .$ docker run --rm guestbook-test printenv APP_VERSIONa93d0e4c7b1f5a28e6c3d9b0f4a7e1c5d2b8f603
--build-arg fills the ARG from the Dockerfile, and --tag gives the image a name. The second command starts a container that only prints the variable: the ID is in the image. Yours is a different one, of course. The pipeline will do exactly this with every commit, so every image knows which commit it was built from, and the footer of the page shows its first seven characters. You can delete the test image again with docker image rm guestbook-test.
Commit
Save the state:
$ git add .$ git commit --message "The app in a container"$ git push
What you have now
The guestbook as an image: built from a recipe, checked by Docker every five seconds, stopped without losing a request, and marked with the commit it came from. So far you build it by hand, on your computer. In the next part, GitHub or GitLab does that for you with every push, and only if the tests pass.
Comments
The comments are GitHub Discussions: sign in with GitHub to write one.
The comments come from GitHub, through giscus. Loading them sends your IP address to giscus.app and GitHub.