[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M79PJQ401RK10NVJ73AH9GFJ":3,"skill-same:01M79PJQ401RK10NVJ73AH9GFJ":43},{"skillNo":4,"name":5,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":20,"frontMatter":21,"refName":22,"commitSha":23,"skillDirectory":24,"forksCount":13,"repositoryHtmlUrl":25,"repositoryHomepageUrl":6,"ownerHtmlUrl":26,"ownerBlogUrl":6,"ownerDescription":27,"updatedAt":28,"install":29,"resources":42},"01M79PJQ401RK10NVJ73AH9GFJ","nodejs-docker-cheat-sheet",null,"JunMystery\u002FAgent-Guidance","JunMystery","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F161468934?v=4","01M79MTMV8F0BY8NK1A92RA8A0","Jun","01M79MTMWCFBKPHN5B25E6V20B",0,"MIT","https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance\u002Fblob\u002Fmain\u002Fskills\u002Fnodejs-docker-cheat-sheet\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"# Node.js Docker Cheat Sheet\n\nThe following cheatsheet provides production-grade guidelines for building optimized and [secure Node.js Docker](https:\u002F\u002Fsnyk.io\u002Fblog\u002F10-best-practices-to-containerize-nodejs-web-applications-with-docker\u002F). You’ll find it helpful regardless of the Node.js application you aim to build. This article will be helpful for you if:\n\n- your aim is to build a frontend application using server-side rendering (SSR) Node.js capabilities for React.\n- you’re looking for advice on how to properly build a Node.js Docker image for your microservices, running Fastify, NestJS or other application frameworks.\n\n## 1) Use explicit and deterministic Docker base image tags\n\nIt may seem to be an obvious choice to build your image based on the `node` Docker image, but what are you actually pulling in when you build the image? Docker images are always referenced by tags, and when you don’t specify a tag the default, `:latest` tag is used.\n\nSo, in fact, by specifying the following in your Dockerfile, you always build the latest version of the Docker image that has been built by the **Node.js Docker working group**:\n\n### FROM node\n\nThe shortcomings of building based on the default `node` image are as follows:\n\n1. Docker image builds are inconsistent. Just like we’re using `lockfiles` to get a deterministic [`npm ci`](https:\u002F\u002Fcheatsheetseries.owasp.org\u002Fcheatsheets\u002FNPM_Security_Cheat_Sheet.html#2-enforce-the-lockfile) behavior every time we install npm packages, we’d also like to get deterministic docker image builds. If we build the image from node—which effectively means the `node:latest` tag—then every build will pull a newly built Docker image of `node`. We don’t want to introduce this sort of non-deterministic behavior.\n2. The node Docker image is based on a full-fledged operating system, full of libraries and tools that you may or may not need to run your Node.js web application. This has two downsides. Firstly a bigger image means a bigger download size which, besides increasing the storage requirement, means more time to download and re-build the image. Secondly, it means you’re potentially introducing security vulnerabilities, that may exist in all of these libraries and tools, into the image.\n\nIn fact, the `node` Docker image is quite big and includes hundreds of security vulnerabilities of different types and severities. If you’re using it, then by default your starting point is going to be a baseline of 642 security vulnerabilities, and hundreds of megabytes of image data that is downloaded on every pull and build.\n\nThe recommendations for building better Docker images are:\n\n1. Use small Docker images—this will translate to a smaller software footprint on the Docker image reducing the potential vulnerability vectors, and a smaller size, which will speed up the image build process\n2. Use the Docker image digest, which is the static SHA256 hash of the image. This ensures that you are getting deterministic Docker image builds from the base image.\n\nBased on this, let’s ensure that we use the Long Term Support (LTS) version of Node.js, and the minimal `alpine` image type to have the smallest size and software footprint on the image:\n\n### FROM node:lts-alpine\n\nNonetheless, this base image directive will still pull new builds of that tag. We can find the `SHA256` hash for it in the [Docker Hub for this Node.js tag](https:\u002F\u002Fhub.docker.com\u002Flayers\u002Fnode\u002Flibrary\u002Fnode\u002Flts-alpine\u002Fimages\u002Fsha256-51e341881c2b77e52778921c685e711a186a71b8c6f62ff2edfc6b6950225a2f?context=explore), or by running the following command once we pulled this image locally, and locate the `Digest` field in the output:\n\n    $ docker pull node:lts-alpine\n    lts-alpine: Pulling from library\u002Fnode\n    0a6724ff3fcd: Already exists\n    9383f33fa9f3: Already exists\n    b6ae88d676fe: Already exists\n    565e01e00588: Already exists\n    Digest: sha256:b2da3316acdc2bec442190a1fe10dc094e7ba4121d029cb32075ff59bb27390a\n    Status: Downloaded newer image for node:lts-alpine\n    docker.io\u002Flibrary\u002Fnode:lts-alpine\n\nAnother way to find the `SHA256` hash is by running the following command:\n\n    $ docker images --digests\n    REPOSITORY                     TAG              DIGEST                                                                    IMAGE ID       CREATED             SIZE\n    node                           lts-alpine       sha256:b2da3316acdc2bec442190a1fe10dc094e7ba4121d029cb32075ff59bb27390a   51d926a5599d   2 weeks ago         116MB\n\nNow we can update the Dockerfile for this Node.js Docker image as follows:\n\n    FROM node@sha256:b2da3316acdc2bec442190a1fe10dc094e7ba4121d029cb32075ff59bb27390a\n    WORKDIR \u002Fusr\u002Fsrc\u002Fapp\n    COPY . \u002Fusr\u002Fsrc\u002Fapp\n    RUN npm ci\n    CMD \"npm\" \"start\"\n\nHowever, the Dockerfile above, only specifies the Node.js Docker image name without an image tag which creates ambiguity for which exact image tag is being used—it’s not readable, hard to maintain and doesn’t create a good developer experience.\n\nLet’s fix it by updating the Dockerfile, providing the full base image tag for the Node.js version that corresponds to that `SHA256` hash:\n\n    FROM node:lts-alpine@sha256:b2da3316acdc2bec442190a1fe10dc094e7ba4121d029cb32075ff59bb27390a\n    WORKDIR \u002Fusr\u002Fsrc\u002Fapp\n    COPY . \u002Fusr\u002Fsrc\u002Fapp\n    RUN npm ci\n    CMD \"npm\" \"start\"\n\n## 2) Install only production dependencies in the Node.js Docker image\n\nThe following Dockerfile directive installs all dependencies in the container, including `devDependencies`, which aren’t needed for a functional application to work. It adds an unneeded security risk from packages used as development dependencies, as well as inflating the image size unnecessarily.\n\n**`RUN npm ci`**\n\nEnforce deterministic builds with `npm ci`. This prevents surprises in a continuous integration (CI) flow because it halts if any deviations from the lockfile are made.\n\nIn the case of building a Docker image for production we want to ensure that we only install production dependencies in a deterministic way, and this brings us to the following recommendation for the best practice for installing npm dependencies in a container image:\n\n**`RUN npm ci --omit=dev`**\n\nThe updated Dockerfile contents in this stage are as follows:\n\n    FROM node:lts-alpine@sha256:b2da3316acdc2bec442190a1fe10dc094e7ba4121d029cb32075ff59bb27390a\n    WORKDIR \u002Fusr\u002Fsrc\u002Fapp\n    COPY . \u002Fusr\u002Fsrc\u002Fapp\n    RUN npm ci --omit=dev\n    CMD \"npm\" \"start\"\n\n## 3) Optimize Node.js tooling for production\n\nWhen you build your Node.js Docker image for production, you want to ensure that all frameworks and libraries are using the optimal settings for performance and security.\n\nThis brings us to add the following Dockerfile directive:\n\n**`ENV NODE_ENV production`**\n\nAt first glance, this looks redundant, since we already specified only production dependencies in the `npm ci` phase—so why is this necessary?\n\nDevelopers mostly associate the `NODE_ENV=production` environment variable setting with the installation of production-related dependencies, however, this setting also has other effects which we need to be aware of.\n\nSome frameworks and libraries may only turn on the optimized configuration that is suited to production if that `NODE_ENV` environment variable is set to `production`. Putting aside our opinion on whether this is a good or bad practice for frameworks to take, it is important to know this.\n\nAs an example, the [Express documentation](https:\u002F\u002Fexpressjs.com\u002Fen\u002Fadvanced\u002Fbest-practice-performance.html#set-node_env-to-production) outlines the importance of setting this environment variable for enabling performance and security related optimizations:\n\nThe performance impact of the `NODE_ENV` variable could be very significant.\n\nMany of the other libraries that you are relying on may also expect this variable to be set, so we should set this in our Dockerfile.\n\nThe updated Dockerfile should now read as follows with the `NODE_ENV` environment variable setting baked in:\n\n    FROM node:lts-alpine@sha256:b2da3316acdc2bec442190a1fe10dc094e7ba4121d029cb32075ff59bb27390a\n    ENV NODE_ENV production\n    WORKDIR \u002Fusr\u002Fsrc\u002Fapp\n    COPY . \u002Fusr\u002Fsrc\u002Fapp\n    RUN npm ci --omit=dev\n    CMD \"npm\" \"start\"\n\n## 4) Don’t run containers as root\n\nThe principle of least privilege is a long-time security control from the early days of Unix and we should always follow this when we’re running our containerized Node.js web applications.\n\nThe threat assessment is pretty straight-forward—if an attacker is able to compromise the web application in a way that allows for [command injection](https:\u002F\u002Fowasp.org\u002Fwww-community\u002Fattacks\u002FCommand_Injection) or [directory path traversal](https:\u002F\u002Fowasp.org\u002Fwww-community\u002Fattacks\u002FPath_Traversal), then these will be invoked with the user who owns the application process. If that process happens to be root then they can do virtually everything within the container, including [attempting a container escape or [privilege escalation](https:\u002F\u002Fowasp.org\u002Fwww-project-web-security-testing-guide\u002Flatest\u002F4-Web_Application_Security_Testing\u002F05-Authorization_Testing\u002F03-Testing_for_Privilege_Escalation). Why would we want to risk it? You’re right, we don’t.\n\nRepeat after me: **“friends don’t let friends run containers as root!”**\n\nThe official `node` Docker image, as well as its variants like `alpine`, include a least-privileged user of the same name: `node`. However, it’s not enough to just run the process as `node`. For example, the following might not be ideal for an application to function well:\n\n    USER node\n    CMD \"npm\" \"start\"\n\nThe reason for that is the `USER` Dockerfile directive only ensures that the process is owned by the `node` user. What about all the files we copied earlier with the `COPY` instruction? They are owned by root. That’s how Docker works by default.\n\nThe complete and proper way of dropping privileges is as follows, also showing our up to date Dockerfile practices up to this point:\n\n    FROM node:lts-alpine@sha256:b2da3316acdc2bec442190a1fe10dc094e7ba4121d029cb32075ff59bb27390a\n    ENV NODE_ENV production\n    WORKDIR \u002Fusr\u002Fsrc\u002Fapp\n    COPY --chown=node:node . \u002Fusr\u002Fsrc\u002Fapp\n    RUN npm ci --omit=dev\n    USER node\n    CMD \"npm\" \"start\"\n\n## 5) Properly handle events to safely terminate a Node.js Docker web application\n\nOne of the most common mistakes I see with blogs and articles about containerizing Node.js applications when running in Docker containers is the way that they invoke the process. All of the following and their variants are bad patterns you should avoid:\n\n- `CMD “npm” “start”`\n- `CMD [“yarn”, “start”]`\n- `CMD “node” “server.js”`\n- `CMD “start-app.sh”`\n\nLet’s dig in! I’ll walk you through the differences between them and why they’re all patterns to avoid.\n\nThe following concerns are key to understanding the context for properly running and terminating Node.js Docker applications:\n\n1. An orchestration engine, such as Docker Swarm, Kubernetes, or even just Docker engine itself, needs a way to send signals to the process in the container. Mostly, these are signals to terminate an application, such as `SIGTERM` and `SIGKILL`.\n2. The process may run indirectly, and if that happens then it’s not always guaranteed that it will receive these signals.\n3. The Linux kernel treats processes that run as process ID 1 (PID) differently than any other process ID.\n\nEquipped with that knowledge, let’s begin investigating the ways of invoking the process for a container, starting off with the example from the Dockerfile we’re building:\n\n**`CMD \"npm\" \"start\"`**\n\nThe caveat here is two fold. Firstly, we’re indirectly running the node application by directly invoking the npm client. Who’s to say that the npm CLI forwards all events to the node runtime? It actually doesn’t, and we can easily test that.\n\nMake sure that in your Node.js application you set an event handler for the `SIGHUP` signal which logs to the console every time you’re sending an event. A simple code example should look as follows:\n\n    function handle(signal) {\n       console.log(`*^!@4=> Received event: ${signal}`)\n    }\n    process.on('SIGHUP', handle)\n\nThen run the container, and once it’s up specifically send it the `SIGHUP` signal using the `docker` CLI and the special `--signal` command-line flag:\n\n**`$ docker kill --signal=SIGHUP elastic_archimedes`**\n\nNothing happened, right? That’s because the npm client doesn’t forward any signals to the node process that it spawned.\n\nThe other caveat has to do with the different ways in which way you can specify the `CMD` directive in the Dockerfile. There are two ways, and they are not the same:\n\n1. the shellform notation, in which the container spawns a shell interpreter that wraps the process. In such cases, the shell may not properly forward signals to your process.\n2. the execform notation, which directly spawns a process without wrapping it in a shell. It is specified using the JSON array notation, such as: `CMD [“npm”, “start”]`. Any signals sent to the container are directly sent to the process.\n\nBased on that knowledge, we want to improve our Dockerfile process execution directive as follows:\n\n**`CMD [\"node\", \"server.js\"]`**\n\nWe are now invoking the node process directly, ensuring that it receives all of the signals sent to it, without it being wrapped in a shell interpreter.\n\nHowever, this introduces another pitfall.\n\nWhen processes run as PID 1 they effectively take on some of the responsibilities of an init system, which is typically responsible for initializing an operating system and processes. The kernel treats PID 1 in a different way than it treats other process identifiers. This special treatment from the kernel means that the handling of a `SIGTERM` signal to a running process won’t invoke a default fallback behavior of killing the process if the process doesn’t already set a handler for it.\n\n\u003C!-- textlint-disable terminology -->\nTo [quote the Node.js Docker working group recommendation](https:\u002F\u002Fgithub.com\u002Fnodejs\u002Fdocker-node\u002Fblob\u002Fmaster\u002Fdocs\u002FBestPractices.md#handling-kernel-signals) on this:  “Node.js was not designed to run as PID 1 which leads to unexpected behaviour when running inside of Docker. For example, a Node.js process running as PID 1 will not respond to SIGINT (CTRL-C) and similar signals”.\n\u003C!-- textlint-enable terminology -->\n\nThe way to go about it then is to use a tool that will act like an init process, in that it is invoked with PID 1, then spawns our Node.js application as another process while ensuring that all signals are proxied to that Node.js process. If possible, we’d like a small as possible tooling footprint for doing so to not risk having security vulnerabilities added to our container image.\n\nOne such tool is [dumb-init](https:\u002F\u002Fengineeringblog.yelp.com\u002F2016\u002F01\u002Fdumb-init-an-init-for-docker.html) which is statically linked and has a small footprint. Here’s how we’ll set it up:\n\n    RUN apk add dumb-init\n    CMD [\"dumb-init\", \"node\", \"server.js\"]\n\nThis brings us to the following up to date Dockerfile. You’ll notice that we placed the `dumb-init` package install right after the image declaration, so we can take advantage of Docker’s caching of layers:\n\n    FROM node:lts-alpine@sha256:b2da3316acdc2bec442190a1fe10dc094e7ba4121d029cb32075ff59bb27390a\n    RUN apk add dumb-init\n    ENV NODE_ENV production\n    WORKDIR \u002Fusr\u002Fsrc\u002Fapp\n    COPY --chown=node:node . .\n    RUN npm ci --omit=dev\n    USER node\n    CMD [\"dumb-init\", \"node\", \"server.js\"]\n\nGood to know: `docker kill` and `docker stop` commands only send signals to the container process with PID 1. If you’re running a shell script that runs your Node.js application, then take note that a shell instance—such as `\u002Fbin\u002Fsh`, for example—doesn’t forward signals to child processes, which means your app will never get a `SIGTERM`.\n\n## 6) Graceful tear down for your Node.js web applications\n\nIf we’re already discussing process signals that terminate applications, let’s make sure we’re shutting them down properly and gracefully without disrupting users.\n\nWhen a Node.js application receives an interrupt signal, also known as `SIGINT`, or `CTRL+C`, it will cause an abrupt process kill, unless any event handlers were set of course to handle it in a different behavior. This means that connected clients to a web application will be immediately disconnected. Now, imagine hundreds of Node.js web containers orchestrated by Kubernetes, going up and down as needs arise to scale or manage errors. Not the greatest user experience.\n\nYou can easily simulate this problem. Here’s a stock Fastify web application example, with an inherent delayed response of 60 seconds for an endpoint:\n\n    fastify.get('\u002Fdelayed', async (request, reply) => {\n     const SECONDS_DELAY = 60000\n     await new Promise(resolve => {\n         setTimeout(() => resolve(), SECONDS_DELAY)\n     })\n     return { hello: 'delayed world' }\n    })\n     \n    const start = async () => {\n     try {\n       await fastify.listen(PORT, HOST)\n       console.log(`*^!@4=> Process id: ${process.pid}`)\n     } catch (err) {\n       fastify.log.error(err)\n       process.exit(1)\n     }\n    }\n     \n    start()\n\nRun this application and once it’s running send a simple HTTP request to this endpoint:\n\n`$ time curl https:\u002F\u002Flocalhost:3000\u002Fdelayed`\n\nHit `CTRL+C` in the running Node.js console window and you’ll see that the curl request exited abruptly. This simulates the same experience your users would receive when containers tear down.\n\nTo provide a better experience, we can do the following:\n\n1. Set an event handler for the various termination signals like `SIGINT` and `SIGTERM`.\n2. The handler waits for clean up operations like database connections, ongoing HTTP requests and others.\n3. The handler then terminates the Node.js process.\n\nSpecifically with Fastify, we can have our handler call on [fastify.close()](https:\u002F\u002Ffastify.dev\u002Fdocs\u002Flatest\u002FReference\u002FServer\u002F#close) which returns a promise that we will await, and Fastify will also take care to respond to every new connection with the HTTP status code 503 to signal that the application is unavailable.\n\nLet’s add our event handler:\n\n    async function closeGracefully(signal) {\n       console.log(`*^!@4=> Received signal to terminate: ${signal}`)\n     \n       await fastify.close()\n       \u002F\u002F await db.close() if we have a db connection in this app\n       \u002F\u002F await other things we should cleanup nicely\n       process.exit()\n    }\n    process.on('SIGINT', closeGracefully)\n    process.on('SIGTERM', closeGracefully)\n\nAdmittedly, this is more of a generic web application concern than Dockerfile related, but is even more important in orchestrated environments.\n\n## 7) Find and fix security vulnerabilities in your Node.js docker image\n\nSee [Docker Security Cheat Sheet - Use static analysis tools](https:\u002F\u002Fcheatsheetseries.owasp.org\u002Fcheatsheets\u002FDocker_Security_Cheat_Sheet.html#rule-9-integrate-container-scanning-tools-into-your-cicd-pipeline)\n\n## 8) Use multi-stage builds\n\nMulti-stage builds are a great way to move from a simple, yet potentially erroneous Dockerfile, into separated steps of building a Docker image, so we can avoid leaking sensitive information. Not only that, but we can also use a bigger Docker base image to install our dependencies, compile any native npm packages if needed, and then copy all these artifacts into a small production base image, like our alpine example.\n\n### Prevent sensitive information leak\n\nThe use-case here to avoid sensitive information leakage is more common than you think.\n\nIf you’re building Docker images for work, there’s a high chance that you also maintain private npm packages. If that’s the case, then you probably needed to find some way to make that secret `NPM_TOKEN` available to the npm install.\n\nHere’s an example for what I’m talking about:\n\n    FROM node:lts-alpine@sha256:b2da3316acdc2bec442190a1fe10dc094e7ba4121d029cb32075ff59bb27390a\n    RUN apk add dumb-init\n    ENV NODE_ENV production\n    ENV NPM_TOKEN 1234\n    WORKDIR \u002Fusr\u002Fsrc\u002Fapp\n    COPY --chown=node:node . .\n    #RUN npm ci --omit=dev\n    RUN echo \"\u002F\u002Fregistry.npmjs.org\u002F:_authToken=$NPM_TOKEN\" > .npmrc && \\\n       npm ci --omit=dev\n    USER node\n    CMD [\"dumb-init\", \"node\", \"server.js\"]\n\nDoing this, however, leaves the `.npmrc` file with the secret npm token inside the Docker image. You could attempt to improve it by deleting it afterwards, like this:\n\n    RUN echo \"\u002F\u002Fregistry.npmjs.org\u002F:_authToken=$NPM_TOKEN\" > .npmrc && \\\n       npm ci --omit=dev\n    RUN rm -rf .npmrc\n\nHowever, now the `.npmrc` file is available in a different layer of the Docker image. If this Docker image is public, or someone is able to access it somehow, then your token is compromised. A better improvement would be as follows:\n\n    RUN echo \"\u002F\u002Fregistry.npmjs.org\u002F:_authToken=$NPM_TOKEN\" > .npmrc && \\\n       npm ci --omit=dev; \\\n       rm -rf .npmrc\n\nThe problem now is that the Dockerfile itself needs to be treated as a secret asset, because it contains the secret npm token inside it.\n\nLuckily, Docker supports a way to pass arguments into the build process:\n\n    ARG NPM_TOKEN\n    RUN echo \"\u002F\u002Fregistry.npmjs.org\u002F:_authToken=$NPM_TOKEN\" > .npmrc && \\\n       npm ci --omit=dev; \\\n       rm -rf .npmrc\n\nAnd then we build it as follows:\n\n**`$ docker build . -t nodejs-tutorial --build-arg NPM_TOKEN=1234`**\n\nI know you were thinking that we’re all done at this point but, sorry to disappoint 🙂\n\nThat’s how it is with security—sometimes the obvious things are yet just another pitfall.\n\nWhat’s the problem now, you ponder? Build arguments passed like that to Docker are kept in the history log. Let’s see with our own eyes. Run this command:\n\n**`$ docker history nodejs-tutorial`**\n\nwhich prints the following:\n\n    IMAGE          CREATED              CREATED BY                                      SIZE      COMMENT\n    b4c2c78acaba   About a minute ago   CMD [\"dumb-init\" \"node\" \"server.js\"]            0B        buildkit.dockerfile.v0\n    \u003Cmissing>      About a minute ago   USER node                                       0B        buildkit.dockerfile.v0\n    \u003Cmissing>      About a minute ago   RUN |1 NPM_TOKEN=1234 \u002Fbin\u002Fsh -c echo \"\u002F\u002Freg…   5.71MB    buildkit.dockerfile.v0\n    \u003Cmissing>      About a minute ago   ARG NPM_TOKEN                                   0B        buildkit.dockerfile.v0\n    \u003Cmissing>      About a minute ago   COPY . . # buildkit                             15.3kB    buildkit.dockerfile.v0\n    \u003Cmissing>      About a minute ago   WORKDIR \u002Fusr\u002Fsrc\u002Fapp                            0B        buildkit.dockerfile.v0\n    \u003Cmissing>      About a minute ago   ENV NODE_ENV=production                         0B        buildkit.dockerfile.v0\n    \u003Cmissing>      About a minute ago   RUN \u002Fbin\u002Fsh -c apk add dumb-init # buildkit     1.65MB    buildkit.dockerfile.v0\n\nDid you spot the secret npm token there? That’s what I mean.\n\nThere’s a great way to manage secrets for the container image, but this is the time to introduce multi-stage builds as a mitigation for this issue, as well as showing how we can build minimal images.\n\n### Introducing multi-stage builds for Node.js Docker images\n\nJust like that principle in software development of Separation of Concerns, we’ll apply the same ideas in order to build our Node.js Docker images. We’ll have one image that we use to build everything that we need for the Node.js application to run, which in a Node.js world, means installing npm packages, and compiling native npm modules if necessary. That will be our first stage.\n\nThe second Docker image, representing the second stage of the Docker build, will be the production Docker image. This second and last stage is the image that we actually optimize for and publish to a registry, if we have one. That first image that we’ll refer to as the `build` image, gets discarded and is left as a dangling image in the Docker host that built it, until it gets cleaned.\n\nHere is the update to our Dockerfile that represents our progress so far, but separated into two stages:\n\n    # --------------> The build image\n    FROM node:latest AS build\n    ARG NPM_TOKEN\n    WORKDIR \u002Fusr\u002Fsrc\u002Fapp\n    COPY package*.json \u002Fusr\u002Fsrc\u002Fapp\u002F\n    RUN echo \"\u002F\u002Fregistry.npmjs.org\u002F:_authToken=$NPM_TOKEN\" > .npmrc && \\\n       npm ci --omit=dev && \\\n       rm -f .npmrc\n     \n    # --------------> The production image\n    FROM node:lts-alpine@sha256:b2da3316acdc2bec442190a1fe10dc094e7ba4121d029cb32075ff59bb27390a\n    RUN apk add dumb-init\n    ENV NODE_ENV production\n    USER node\n    WORKDIR \u002Fusr\u002Fsrc\u002Fapp\n    COPY --chown=node:node --from=build \u002Fusr\u002Fsrc\u002Fapp\u002Fnode_modules \u002Fusr\u002Fsrc\u002Fapp\u002Fnode_modules\n    COPY --chown=node:node . \u002Fusr\u002Fsrc\u002Fapp\n    CMD [\"dumb-init\", \"node\", \"server.js\"]\n\nAs you can see, I chose a bigger image for the `build` stage because I might need tooling like `gcc` (the GNU Compiler Collection) to compile native npm packages, or for other needs.\n\nIn the second stage, there’s a special notation for the `COPY` directive that copies the `node_modules\u002F` folder from the build Docker image into this new production base image.\n\nAlso, now, do you see that `NPM_TOKEN` passed as build argument to the `build` intermediary Docker image? It’s not visible anymore in the `docker history nodejs-tutorial` command output because it doesn’t exist in our production docker image.\n\n## 9) Keeping unnecessary files out of your Node.js Docker images\n\nYou have a `.gitignore` file to avoid polluting the git repository with unnecessary files, and potentially sensitive files too, right? The same applies to Docker images.\n\nDocker has a `.dockerignore` which will ensure it skips sending any glob pattern matches inside it to the Docker daemon. Here is a list of files to give you an idea of what you might be putting into your Docker image that we’d ideally want to avoid:\n\n    .dockerignore\n    node_modules\n    npm-debug.log\n    Dockerfile\n    .git\n    .gitignore\n\nAs you can see, the `node_modules\u002F` is actually quite important to skip because if we hadn’t ignored it, then the simplistic Dockerfile version that we started with would have caused the local `node_modules\u002F` folder to be copied over to the container as-is.\n\n    FROM node@sha256:b2da3316acdc2bec442190a1fe10dc094e7ba4121d029cb32075ff59bb27390a\n    WORKDIR \u002Fusr\u002Fsrc\u002Fapp\n    COPY . \u002Fusr\u002Fsrc\u002Fapp\n    RUN npm ci\n    CMD \"npm\" \"start\"\n\nIn fact, it’s even more important to have a `.dockerignore` file when you are practicing multi-stage Docker builds. To refresh your memory on how the 2nd stage Docker build looks like:\n\n    # --------------> The production image\n    FROM node:lts-alpine\n    RUN apk add dumb-init\n    ENV NODE_ENV production\n    USER node\n    WORKDIR \u002Fusr\u002Fsrc\u002Fapp\n    COPY --chown=node:node --from=build \u002Fusr\u002Fsrc\u002Fapp\u002Fnode_modules \u002Fusr\u002Fsrc\u002Fapp\u002Fnode_modules\n    COPY --chown=node:node . \u002Fusr\u002Fsrc\u002Fapp\n    CMD [\"dumb-init\", \"node\", \"server.js\"]\n\nThe importance of having a `.dockerignore` is that when we do a `COPY . \u002Fusr\u002Fsrc\u002Fapp` from the 2nd Dockerfile stage, we’re also copying over any local node\\_modules\u002F to the Docker image. That’s a big no-no as we may be copying over modified source code inside `node_modules\u002F`.\n\nOn top of that, since we’re using the wildcard `COPY .` we may also be copying into the Docker image sensitive files that include credentials or local configuration.\n\nThe take-away here for a `.dockerignore` file is:\n\n- Skip potentially modified copies of `node_modules\u002F` in the Docker image.\n- Saves you from secrets exposure such as credentials in the contents of `.env` or `aws.json` files making their way into the Node.js Docker image.\n- It helps speed up Docker builds because it ignores files that would have otherwise caused a cache invalidation. For example, if a log file was modified, or a local environment configuration file, all would’ve caused the Docker image cache to invalidate at that layer of copying over the local directory.\n\n## 10) Mounting secrets into the Docker build image\n\nOne thing to note about the `.dockerignore` file is that it is an all or nothing approach and can’t be turned on or off per build stages in a Docker multi-stage build.\n\nWhy is it important? Ideally, we would want to use the `.npmrc` file in the build stage, as we may need it because it includes a secret npm token to access private npm packages. Perhaps it also needs a specific proxy or registry configuration to pull packages from.\n\nThis means that it makes sense to have the `.npmrc` file available to the `build` stage—however, we don’t need it at all in the second stage for the production image, nor do we want it there as it may include sensitive information, like the secret npm token.\n\nOne way to mitigate this `.dockerignore` caveat is to mount a local file system that will be available for the build stage, but there’s a better way.\n\nDocker supports a relatively new capability referred to as Docker secrets, and is a natural fit for the case we need with `.npmrc`. Here is how it works:\n\n- When we run the `docker build` command we will specify command-line arguments that define a new secret ID and reference a file as the source of the secret.\n- In the Dockerfile, we will add flags to the `RUN` directive to install the production npm, which mounts the file referred by the secret ID into the target location—the local directory `.npmrc` file which is where we want it available.\n- The `.npmrc` file is mounted as a secret and is never copied into the Docker image.\n- Lastly, let’s not forget to add the `.npmrc` file to the contents of the `.dockerignore` file so it doesn’t make it into the image at all, for either the build nor production images.\n\nLet’s see how all of it works together. First the updated `.dockerignore` file:\n\n    .dockerignore\n    node_modules\n    npm-debug.log\n    Dockerfile\n    .git\n    .gitignore\n    .npmrc\n\nThen, the complete Dockerfile, with the updated RUN directive to install npm packages while specifying the `.npmrc` mount point:\n\n    # --------------> The build image\n    FROM node:latest AS build\n    WORKDIR \u002Fusr\u002Fsrc\u002Fapp\n    COPY package*.json \u002Fusr\u002Fsrc\u002Fapp\u002F\n    RUN --mount=type=secret,mode=0644,id=npmrc,target=\u002Fusr\u002Fsrc\u002Fapp\u002F.npmrc npm ci --omit=dev\n     \n    # --------------> The production image\n    FROM node:lts-alpine\n    RUN apk add dumb-init\n    ENV NODE_ENV production\n    USER node\n    WORKDIR \u002Fusr\u002Fsrc\u002Fapp\n    COPY --chown=node:node --from=build \u002Fusr\u002Fsrc\u002Fapp\u002Fnode_modules \u002Fusr\u002Fsrc\u002Fapp\u002Fnode_modules\n    COPY --chown=node:node . \u002Fusr\u002Fsrc\u002Fapp\n    CMD [\"dumb-init\", \"node\", \"server.js\"]\n\nAnd finally, the command that builds the Node.js Docker image:\n\n    docker build . -t nodejs-tutorial --secret id=npmrc,src=.npmrc\n\n**Note:** Secrets are a new feature in Docker and if you’re using an older version, you might need to enable it Buildkit as follows:\n\n    DOCKER_BUILDKIT=1 docker build . -t nodejs-tutorial --build-arg NPM_TOKEN=1234 --secret id=npmrc,src=.npmrc\n\n## References\n\n- [Node.js Docker: Best Practices](https:\u002F\u002Fgithub.com\u002Fnodejs\u002Fdocker-node\u002Fblob\u002Fmain\u002Fdocs\u002FBestPractices.md)\n- [Docker: Build secrets](https:\u002F\u002Fdocs.docker.com\u002Fbuild\u002Fbuilding\u002Fsecrets\u002F)\n",{},"main","5d0a87185c0e172c3901e2a6e5916b6d544b8b94","skills\u002Fnodejs-docker-cheat-sheet","https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance","https:\u002F\u002Fgithub.com\u002FJunMystery","AI is the typist, I am the architect. Building efficient, secure, and user-centric products through disciplined AI prompt engineering.","2026-11-13 17:41:25",{"source":7,"skillName":5,"commands":30,"prompt":40,"zipAvailable":41},[31,34,37],{"tool":32,"command":33},"npx","npx skills add JunMystery\u002FAgent-Guidance --skill nodejs-docker-cheat-sheet",{"tool":35,"command":36},"bunx","bunx skills add JunMystery\u002FAgent-Guidance --skill nodejs-docker-cheat-sheet",{"tool":38,"command":39},"pnpm","pnpm dlx skills add JunMystery\u002FAgent-Guidance --skill nodejs-docker-cheat-sheet","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance\u002Fblob\u002Fmain\u002Fskills\u002Fnodejs-docker-cheat-sheet\u002FSKILL.md",true,[],[44,50,56,62,68,74],{"skillNo":45,"name":46,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":47,"categories":48,"keywords":49,"publishedAt":18},"01M79QR1E309VJ6CTQKB32AWWA","zero-trust-architecture-cheat-sheet","https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance\u002Fblob\u002Fmain\u002Fskills\u002Fzero-trust-architecture-cheat-sheet\u002FSKILL.md",[],[],{"skillNo":51,"name":52,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":53,"categories":54,"keywords":55,"publishedAt":18},"01M79QQV7GHYR02DYGN41S23WN","xss-filter-evasion-cheat-sheet","https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance\u002Fblob\u002Fmain\u002Fskills\u002Fxss-filter-evasion-cheat-sheet\u002FSKILL.md",[],[],{"skillNo":57,"name":58,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":59,"categories":60,"keywords":61,"publishedAt":18},"01M79QQNSN7YB8XB61FFSCS3WH","xs-leaks-cheat-sheet","https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance\u002Fblob\u002Fmain\u002Fskills\u002Fxs-leaks-cheat-sheet\u002FSKILL.md",[],[],{"skillNo":63,"name":64,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":65,"categories":66,"keywords":67,"publishedAt":18},"01M79QQHZZJKFDY9132G5A65C2","xpath-injection-prevention-cheat-sheet","https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance\u002Fblob\u002Fmain\u002Fskills\u002Fxpath-injection-prevention-cheat-sheet\u002FSKILL.md",[],[],{"skillNo":69,"name":70,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":18},"01M79QQB9ZSD3DJG8658EHQXR1","xml-security-cheat-sheet","https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance\u002Fblob\u002Fmain\u002Fskills\u002Fxml-security-cheat-sheet\u002FSKILL.md",[],[],{"skillNo":75,"name":76,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":18},"01M79QQ60WKV7PFMXWT9CW8PM6","xml-external-entity-prevention-cheat-sheet","https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance\u002Fblob\u002Fmain\u002Fskills\u002Fxml-external-entity-prevention-cheat-sheet\u002FSKILL.md",[],[]]