15 min read
Dockerfile from scratch: the API in a container
In one sentence: A Dockerfile is the recipe of an image: which image you start from, what you copy, what you run when you build it and which program it starts. With eight instructions, the shop's API fits in an image that starts the same way on any computer with Docker, without installing Node or its dependencies.
What you will learn
- Read and write a Dockerfile for a Node API, instruction by instruction.
- Keep your secrets and your computer's dependencies out of the image with .dockerignore.
- Build the image and start it with its configuration, connected to the PostgreSQL on your computer.
- Explain why CMD goes in exec form and how a server that is PID 1 shuts down properly.
Before you start, read: 02-layers.md
The problem
Section titled “The problem”Luis wants to try the shop’s API on his laptop. All he has is Docker: no Node 26, no dependencies. In lesson 1 you started nginx with one command because someone had made its Docker imageA read-only template with the files a program needs (the program itself, its libraries and a minimal system) and the command to start it. You can start as many containers as you want from one image, and none of them changes it.Go to definition. There’s no image of your API: you have to make it yourself.
For that you write a DockerfileThe text file with the recipe for a Docker image, one instruction per line. It says which image to start from, which files to copy, which commands to run while building it and which program each container starts. docker build reads it from top to bottom, and each step that changes files adds a layer.Go to definition: a text file with the steps you did by hand in Phase 3, one per line. docker build reads it and produces the image. From then on, Luis, a server or you yourself a year from now all start exactly the same API.
The analogy
Section titled “The analogy”The analogy
Imagine Ana leaves a recipe for a cook who has never seen her kitchen. It has to be exact: “start from this kitchen, already equipped; work on this counter; take these ingredients from the basket; cook them like this; when the restaurant opens, serve this dish.”
The cook only uses what’s in the basket. That’s why Ana chooses what goes into it, and her wallet, with her house keys, stays out.
Where the analogy breaks down
- The cook cooks every time someone orders. Docker runs the recipe once, when it builds the image; each container starts the dish already made.
- “This kitchen” may change if the owner remodels it. In a Dockerfile, the starting image can be pinned by its fingerprint, and then it never changes.
- The cook remembers what they did last time: that’s the cache from lesson 2.
How it really works
Section titled “How it really works”The shop’s Dockerfile
Section titled “The shop’s Dockerfile”This is the whole file, Dockerfile, with no extension, in the project folder:
# The image of the shop's API (Phase 7, lesson 3). Build it with:# docker build -t shop-api .
# The starting image: Debian with Node 26, in its slim version (node:26-slim). Pinned by its# digest, which never changes: the 26-slim tag, on the other hand, moves to another image with each# version.FROM node:26-slim@sha256:193fe51b64e77981119c98c2002c9e32a70e2f006fb4d25068ce0558998917f0
# The working folder inside the image: the following instructions run in it.WORKDIR /app
# First, only what npm ci needs: this way, changing the code doesn't repeat the install (the cache).# .npmrc too: without it, npm ci would run the packages' install scripts, which .npmrc turns off# (ignore-scripts=true).COPY package.json package-lock.json .npmrc ./
# Installs exactly the versions in package-lock.json.RUN npm ci
# The rest of the project, except what .dockerignore says.COPY . .
# Inside the container, the server listens on all its addresses (src/config.ts).ENV HOST=0.0.0.0
# Documents the port it listens on. It doesn't publish it: docker run -p does that.EXPOSE 3000
# The program the container starts, in exec form (a list): node is process 1 and receives the# signals from docker stop and from Ctrl + C.CMD ["node", "src/server.ts"]The lines with # are comments. Each instruction starts with a word in capitals, and Docker runs them from top to bottom. It’s the same recipe as in the lab of lesson 2. Now, piece by piece.
FROM: the starting image, pinned by its fingerprint
Section titled “FROM: the starting image, pinned by its fingerprint”FROM says which image you start from: everything else is built on top of its layers. node:26-slim is Node 26 on a minimal Debian, the one you looked at with docker history. Lesson 4 compares it with smaller ones.
After it comes @sha256:193f…, its fingerprint (digest). The 26-slim tag moves to another image with each new version of Node or Debian; the fingerprint always names exactly the same one. It’s the idea behind the save-exact in your .npmrc: the version changes when you decide, not when someone publishes. Lesson 8 tells you how to update it.
WORKDIR: the working folder
Section titled “WORKDIR: the working folder”WORKDIR /app creates the folder /app inside the image and goes into it, like a mkdir and a cd. The following instructions work there, and the container will start in it.
COPY and RUN: the dependencies first
Section titled “COPY and RUN: the dependencies first”COPY source destination copies files from your folder into the image. Here it copies three to ./, that is, to /app:
package.jsonandpackage-lock.json: whatnpm cineeds. They go on their own, before the code, because of the cache: changingsrc/won’t repeat the install (lesson 2)..npmrc: the project’s rules for npm. Without it,npm ciinside the image would run each package’s install scripts, exactly what your.npmrcturns off withignore-scripts, and asroot, the userRUNruns as.
RUN npm ci runs a command when the image is built, not when it starts. npm ci installs exactly what the lockfile says, inside a Linux: the dependencies are Linux ones, even if you build on a Mac. It’s the biggest layer: 161 MB.
COPY . . and the .dockerignore: what goes into the image
Section titled “COPY . . and the .dockerignore: what goes into the image”COPY . . copies the rest of the project to /app. The first dot is the folder you gave docker build, the context: Docker packs it up and sends it to the engine. What isn’t in the context, COPY can’t find.
A .dockerignore file, next to the Dockerfile, says what stays out, like .gitignore for Git:
# What doesn't go into the image: docker build doesn't send it, and COPY . . doesn't find it.
# The dependencies are installed inside, with npm ci, for Linux: the ones on your computer may be# for another system, and they're heavy.node_modules
# Your secrets. An image is shared, and whoever has it can read all its files: the configuration# arrives at startup, with --env-file or -e..env
# The Git history, the logs and the Docker files, which the API doesn't use..git*.logDockerfile.dockerignoreLine by line:
node_modules: your dependencies, maybe installed for macOS. The image has its own, fromnpm ci; copying yours on top would overwrite them..env: your SecretA piece of data that gives access to something and that only the people and programs that need it should know, like a database password or an API key. It’s never written inside the code.Go to definition. An image gets shared, and whoever has it can read all its files. It’s the rule from Phase 1 and from lesson 8 of Phase 6: a secret that travels in an image is as leaked as one that made it into Git..git,*.log,Dockerfileand.dockerignore: the Git history, the logs and Docker’s own files. The API doesn’t use them.
The tests, test/, do go in: in lesson 4, the type check done during the build checks them too.
ENV HOST=0.0.0.0: listening on every address
Section titled “ENV HOST=0.0.0.0: listening on every address”ENV leaves an Environment variableA name with a value, like PORT=3000, that a program receives when it starts from whoever starts it, for example the shell. It lets you configure the program without changing its code and give it secrets without writing them in it.Go to definition in the image’s record: all its containers start with it. From this step on, src/config.ts reads HOST, the address the server listens on, and src/server.ts uses it:
// ws does the WebSocket work. noServer: it doesn't open another port; the connections arrive// through the same one as the API, and Hono decides on which route they're accepted (/echo).const webSockets = new WebSocketServer({ noServer: true });
// hostname: the address it listens on, 127.0.0.1 except in a container (config.ts).const server = serve( { fetch: app.fetch, port: config.PORT, hostname: config.HOST, websocket: { server: webSockets } }, (info) => { log.info(`The shop is listening on http://localhost:${info.port}`); },);Without HOST, the server listens on 127.0.0.1, as it has since Phase 3: only your computer reaches it. Inside a container, 127.0.0.1 is the container itself. What arrives through the published port comes in through the container’s network, not through its 127.0.0.1, so nobody would reach it. 0.0.0.0 means “all my addresses.”
Does that break the rule from Phase 3? No: who reaches the container is decided by the published port. With -p 127.0.0.1:3000:3000, only your computer. Lesson 6 goes into it in depth.
ENV is for default values, never for secrets: docker history shows every ENV to whoever has the image.
EXPOSE: it only documents
Section titled “EXPOSE: it only documents”EXPOSE 3000 notes in the record that the program listens on 3000. It doesn’t open or publish anything: docker run -p does that. It’s there for whoever reads the Dockerfile, and for some tools.
CMD in exec form: node is PID 1
Section titled “CMD in exec form: node is PID 1”CMD says which program each container starts. It goes in exec form, a list in square brackets: ["node", "src/server.ts"]. Docker starts node directly, and node is PIDPID stands for Process Identifier.The number the operating system uses to identify each process while it’s running. It lets you address a specific process, for example to stop it.Go to definition 1.
There’s another form, the shell form: CMD node src/server.ts, without brackets. Docker turns it into sh -c "node src/server.ts". Then PID 1 is sh, and node is its child. docker stop sends SIGTERM to PID 1, sh doesn’t pass it on to node, and ten seconds later SIGKILL arrives. You’ll check it in the challenge in “Try it.”
The Node image first starts a script of its own, docker-entrypoint.sh, which replaces itself with your CMD without leaving a trace: node is still number 1.
Shutting down properly: PID 1 and signals
Section titled “Shutting down properly: PID 1 and signals”As you saw in lesson 1, Linux doesn’t end PID 1 with a SignalA short notice the operating system delivers to a process, like “interrupt yourself” or “finish”. Each signal is a number with a name, like SIGTERM, and pressing Ctrl+C in the terminal sends one.Go to definition it hasn’t prepared for. That’s why server.ts prepares for two:
// Shutting down properly. docker stop sends the SIGTERM signal, and Ctrl + C, SIGINT (Phase 1). In// a container, the server is process 1, and Linux doesn't end process 1 with a signal nobody// listens to: without this, docker stop would wait 10 seconds and kill it with SIGKILL, cutting off// whatever was halfway done. This way, it stops accepting connections, finishes the requests it// has and closes the connections to PostgreSQL.for (const signal of ['SIGTERM', 'SIGINT'] as const) { process.once(signal, () => { log.info(`${signal}: the shop is shutting down`); server.close(async () => { await pool.end(); process.exit(0); }); // A connection that never ends (an order's events, a WebSocket) doesn't hold it for more than // 5 seconds. setTimeout(() => process.exit(0), 5000).unref(); });}for (const signal of ['SIGTERM', 'SIGINT']): the same forSIGTERM, the one fromdocker stop, andSIGINT, the one from Ctrl + C (Phase 1).process.once(signal, …): the function runs the first time that signal arrives.server.close(…): stops accepting connections and waits for the requests halfway through to finish. Thenpool.end()closes the connections to PostgreSQL andprocess.exit(0)ends with code 0, “all good.”setTimeout(…, 5000).unref(): if a connection never ends, like an open WebSocketA protocol for the client and the server to send each other messages in both directions, whenever they want, over a single connection that stays open. It starts as an HTTP request that asks to switch protocols, and the server accepts with status code 101.Go to definition, it exits anyway after 5 seconds.unref()stops that timer, on its own, from keeping the program alive.
Without this, docker stop takes ten seconds and cuts off whatever was halfway done. With it, less than two tenths of a second.
The database is outside the container
Section titled “The database is outside the container”Your .env says DATABASE_URL=postgres://shop:shop@localhost:5432/shop. Inside the container, localhost is the container, and there’s no PostgreSQL there: the API would answer 500 and its log would say connect ECONNREFUSED 127.0.0.1:5432.
How to reach the PostgreSQL on your computer depends on your Docker:
- Docker Desktop gives containers a name for the computer they run on:
host.docker.internal. All you need is to changelocalhostto that name. - On Linux, with Docker Engine, that name doesn’t exist, and even if you added it, your PostgreSQL only accepts connections from
localhost. Opening it to Docker’s network means touching its configuration.--network hostis easier: the container has no network of its own, it uses your Linux’s, and itslocalhostis yours. Since the server ends up on your network,HOSTgoes back to127.0.0.1.
In lessons 5 and 6, PostgreSQL moves into a container and the API finds it by its name, the same on every system.
Try it
Section titled “Try it”The goal: put the shop in an image, call it with curl and find out how long it takes to stop with and without its SIGTERM.
The outputs are from Docker Engine 29 on a Mac, inside a virtual machine with Linux, like Docker Desktop’s. We captured them with another port and other names, which we’ve changed to the lesson’s: nothing else changes. Your IDs, fingerprints, sizes and times will be different.
Update your project
Section titled “Update your project”You start from your project from lesson 8 of Phase 6. Download this lesson’s step and copy the two Docker files, the two files in src/ that change and their test:
cd ~/backend-course/phase-3curl -O https://backenddesdecero.com/practicas/shop-api/32-dockerfile.tar.gztar -xzf 32-dockerfile.tar.gzcd shop-apicp ../32-dockerfile/Dockerfile ../32-dockerfile/.dockerignore .cp ../32-dockerfile/src/config.ts ../32-dockerfile/src/server.ts src/cp ../32-dockerfile/test/docker.test.ts test/If your npm start is running, stop it with Ctrl + C: the container will need port 3000. PostgreSQL, on the other hand, has to be running.
1. Build the image
docker build -t shop-api .What you will see:
[+] Building 8.2s (10/10) FINISHED docker:colima=> [internal] load build definition from Dockerfile 0.0s=> => transferring dockerfile: 1.29kB 0.0s=> [internal] load metadata for docker.io/library/node:26-slim@sha256:19 0.0s=> [internal] load .dockerignore 0.0s=> => transferring context: 551B 0.0s=> [1/5] FROM docker.io/library/node:26-slim@sha256:193fe51b64e77981119c 0.0s=> => resolve docker.io/library/node:26-slim@sha256:193fe51b64e77981119c 0.0s=> [internal] load build context 0.0s=> => transferring context: 512.14kB 0.0s=> CACHED [2/5] WORKDIR /app 0.0s=> [3/5] COPY package.json package-lock.json .npmrc ./ 0.1s=> [4/5] RUN npm ci 3.9s=> [5/5] COPY . . 0.1s=> exporting to image 4.0s=> => exporting layers 3.1s…=> => naming to docker.io/library/shop-api:latest 0.0s=> => unpacking to docker.io/library/shop-api:latest 0.9sWord by word: docker build builds an image; -t shop-api gives it a name, with the tag latest; and . is the context, the current folder.
While it builds, the lines rewrite themselves; when it finishes, this summary is left:
load build context: what your folder sends, 512 kB. Without.dockerignore, withnode_modules, it would be hundreds of MB.[1/5]to[5/5]: your five steps with a layer, with their seconds.npm ciis the slow one; the first time, with the downloads, it will take longer.docker:colima, at the top right, is the Docker that built it: we captured with Colima, another program that starts the engine in a virtual machine. You’ll seedocker:desktop-linuxordocker:default. OurWORKDIRcame outCACHEDbecause of an earlier image with the same beginning.
If it ends with open Dockerfile: no such file or directory, you’re not in the project folder, or you didn’t copy the Dockerfile.
2. What’s inside?
docker image ls shop-apidocker run --rm shop-api ls -aWhat you will see:
IMAGE ID DISK USAGE CONTENT SIZE EXTRAshop-api:latest c6f29c6cd282 596MB 145MB....env.example.gitignore.npmrc.nvmrcdbdrizzledrizzle.config.tsexamplesnode_modulespackage-lock.jsonpackage.jsonscriptssrctesttsconfig.jsonThe image downloads 145 MB compressed and takes up 596 MB on your disk, as you saw in lesson 2. ls -a replaces node and lists /app: .env.example is there, but your .env isn’t. The node_modules is the one from npm ci.
Now start it. The configuration arrives at startup, from your .env:
3. Start the shop
docker run -d --name shop -p 127.0.0.1:3000:3000 --env-file .env \ -e DATABASE_URL=postgres://shop:shop@host.docker.internal:5432/shop shop-apidocker logs shopWhat you will see:
6038c412f0a8563f0a9e0b7e38517e8892a95bf347d1a65284cb3ba04ece3e03{"level":30,"time":1791955166208,"pid":1,"hostname":"6038c412f0a8","msg":"The shop is listening on http://localhost:3000"}--env-file .env: creates a variable inside for each line of your.env.-e DATABASE_URL=…: changes only that one. If a variable is in both,-ewins.-p 127.0.0.1:3000:3000,-dand--name, as in lesson 1. The\at the end continues the command on the next line.
In the log, look at "pid":1: your server is the first process. hostname is the container’s ID.
On Windows, your PostgreSQL lives in WSL, and a container can’t always reach it. If step 4 returns a 500, see “Common mistakes.”
3. Start the shop
docker run -d --name shop --network host -e HOST=127.0.0.1 --env-file .env shop-apidocker logs shopWhat you will see:
ba26e4dfdcd576636394e127233f63faa5fd6255423515fd7788f6ee678d2bcb{"level":30,"time":1791955246526,"pid":1,"hostname":"laptop","msg":"The shop is listening on http://localhost:3000"}--network host: the container uses your Linux’s network. No-p: port 3000 is already yours.-e HOST=127.0.0.1: the server goes back to listening only on your computer.--env-file .env: creates a variable inside for each line of your.env, includingDATABASE_URLwith itslocalhost, which here is yours.
In the log, look at "pid":1: your server is the first process. With --network host, hostname is your computer’s name; we’ve put laptop.
4. Ask it for the products
curl -s 127.0.0.1:3000/v2/productsWhat you will see:
[{"id":1,"name":"T-shirt","priceCents":2000,"stock":40,"categories":["Clothing"]},{"id":2,"name":"Mug","priceCents":850,"stock":60,"categories":["Home","Gifts"]},{"id":3,"name":"Hoodie","priceCents":3500,"stock":25,"categories":["Clothing"]},{"id":4,"name":"Cap","priceCents":1500,"stock":15,"categories":["Clothing","Gifts"]}]The products in your PostgreSQL, served by an API running in a container, without your Node. Your data may be different if you changed it.
5. Stop it
time docker stop shopdocker logs shop | tail -1What you will see:
shopdocker stop shop 0.01s user 0.01s system 12% cpu 0.153 total{"level":30,"time":1791955170256,"pid":1,"hostname":"6038c412f0a8","msg":"SIGTERM: the shop is shutting down"}0.153 seconds: SIGTERM reached node and the shut-down region closed everything. The last line of the log says so. In bash, time writes real 0m0.153s.
Delete it with docker rm shop: the image stays.
Change one line and rebuild
Section titled “Change one line and rebuild”Now, an experiment. In src/server.ts, remove 'SIGTERM', from the list, so that only 'SIGINT' is left:
for (const signal of ['SIGINT'] as const) {Rebuild, with --progress=plain to read each step as in lesson 2:
6. Which layers run again?
docker build --progress=plain -t shop-api .What you will see:
…#6 [2/5] WORKDIR /app#6 CACHED
#7 [3/5] COPY package.json package-lock.json .npmrc ./#7 CACHED
#8 [4/5] RUN npm ci#8 CACHED
#9 [5/5] COPY . .#9 DONE 0.0s…Only COPY . . runs: its files changed. npm ci comes out of the cache, because package.json, the lockfile and .npmrc are the same. It’s Luis’s order from lesson 2.
Start the shop again with the command from step 3 and, when the log says it’s listening, stop it:
7. Without SIGTERM
time docker stop shopdocker ps -a --filter name=shopWhat you will see:
shopdocker stop shop 0.01s user 0.01s system 0% cpu 10.131 totalCONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES59b9edb87f5d shop-api "docker-entrypoint.s…" 20 seconds ago Exited (137) Less than a second ago shopMore than ten seconds, and Exited (137): 128 plus 9, SIGKILL. Nobody was listening for SIGTERM, PID 1 ignored it, and Docker waited and killed it. --filter name=shop keeps only the containers with that name.
Put 'SIGTERM', back, rebuild and delete the container with docker rm shop.
Challenge: start the image as if CMD were in shell form, with docker run -d --name test --env-file .env shop-api sh -c 'node src/server.ts'. How long does docker stop test take, and which pid does its log say?Show answer
About 10 seconds (10.072 total in our test), and the log’s pid is no longer 1 (your number may be different):
{"level":30,…,"pid":8,…,"msg":"The shop is listening on http://localhost:3000"}PID 1 is sh, which receives SIGTERM and doesn’t pass it on to node, even though node does know how to shut down. The log doesn’t say SIGTERM: the shop is shutting down: node died from SIGKILL. Delete it with docker rm test.
You have already seen it
Section titled “You have already seen it”npm ciandnpm start. They’re the steps from Phase 3:RUN npm ciis your install, andCMDis what yournpm startdoes, without npm in between..gitignore..dockerignoreis its partner: both leave outnode_modulesand.env.- The
pidin your logs. pino has written it on every line since Phase 3. On your computer it’s a big number; in the container, 1.
Common mistakes
Section titled “Common mistakes”- The server listens on
127.0.0.1inside. The log says it’s listening, butcurlanswerscurl: (52) Empty reply from server, or a similar connection error.ENV HOST=0.0.0.0is missing. localhostinDATABASE_URL. The API answers500, anddocker logssaysconnect ECONNREFUSED 127.0.0.1:5432: it’s looking for PostgreSQL inside the container. On Windows, if it doesn’t get through withhost.docker.internaleither, carry on withcurl -s 127.0.0.1:3000/, which doesn’t use the database; lesson 6 solves it.- Secrets in the image. A
.envwithout.dockerignore, or anENV KEY=…, travels with the image to whoever receives it. CMDin shell form.docker stoptakes ten seconds and ends with137.- Changing the code and not rebuilding. The container runs the image, not your folder: after
docker build, delete the container and start another one. port is already allocated. Another program, maybe yournpm start, is using 3000: stop it.
Summary
Section titled “Summary”- A Dockerfile is the recipe of an image:
FROMthe base,WORKDIRthe folder,COPYyour files,RUNcommands at build time,ENVandEXPOSEdata for the record, andCMDthe container’s program. - The base is pinned by its fingerprint, and
.npmrcgoes withpackage.jsonso thatnpm cifollows its rules inside. .dockerignoreleaves outnode_modulesand.env: the secrets arrive at startup, with--env-fileor-e.- Inside a container, the server listens on
0.0.0.0andlocalhostis the container;-p 127.0.0.1:decides who gets in. CMDin exec form makesnodePID 1, and handlingSIGTERMlets it stop in tenths of a second, not in ten seconds.
Did you get it?
Section titled “Did you get it?”To review:
Further reading
Section titled “Further reading”- The Dockerfile reference, from the Docker documentation: every instruction, with the exec form and the shell form.
- Building best practices: Docker’s recommendations for writing a Dockerfile.
- Build context: what
docker buildsends to the engine and how.dockerignoreworks. - The
docker stopreference: the signal, the wait and how to change them.