What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.
A Dockerfile is an ordered set of instructions that Docker turns into an image; writing a production-ready one means controlling that order, the files and dependencies copied into each layer, and the contents of the final runtime stage. Start with a small, readable file, then add cache-aware dependency steps, a multi-stage build, deliberate base-image pinning, BuildKit secrets, and CI validation.
The examples below use a Node.js service whose package.json defines npm run build and whose compiled entry point is dist/server.js. Replace those commands and paths with the ones required by your application rather than treating them as universal Docker commands.
As an Amazon Associate I earn from qualifying purchases.
Recommended Free Tools
What is a Dockerfile, and where does it start?
A Dockerfile is a text document containing instructions that Docker evaluates to assemble an image. Docker processes those instructions in order. In the conventional form, the first instruction is FROM; parser directives, comments, and globally scoped ARG declarations may appear before it. The Dockerfile reference defines the exact behavior of every instruction.
Instruction names are conventionally written in uppercase (FROM, RUN, COPY), while arguments use the spelling required by the command. A comment begins with #. A parser directive such as # syntax=docker/dockerfile:1 must appear before the first non-directive instruction if you want to select a Dockerfile frontend.
Popular on Amazon
- 【90 Degree Full Function USB C Adapter】Supports the latest USB4 standard for up to 40Gbps of bandwidth, 8K video support, and up to 240W Fast charging; Support USB PD 3.1 Extended Power Range (EPR) including 140W, 180W and 240W. Your productivity is easily doubled. *Warm Tip: For the best fit, please make sure the USB-C port is fully exposed; thick or bulky cases may affect compatibility.
- 【Reliable Quality】Made from high-quality, scratch-resistant aluminum alloy, delicate metal frame. get excellent wear resistance and heat dissipation. Non-Slip Design for easier insertion and removal.
- 【Small and portable】Ultra thin size, ultra compact design, a petite physique that matches the minimalist design of your modern laptops. Coming with a slim figure that won't block the port next to the one it's plugged into.
- 【Compatibility】Widely work with most usb c, thunderbolt 4/3 devices. Compatibilit for ROG Ally, Steam Deck, Switch, MacBook Pro, Quest 3 VR headset, Surface Book 2, iPhone 18/17/16/15, Samsung Galaxy S23/S22/S21, Note 20/10, Google Pixel, ChromeBook, etc.
- 【Excellence Customer Support】If you experience any issues or cable failure, simply reach out to our dedicated customer service team. We provide a prompt response within 18 hours, providing you with the necessary technical support to resolve any concerns.
Build a file named Dockerfile in the project directory, then run docker build -t example-api .. The final dot is the build context: Docker can send files from that directory to the builder, subject to your .dockerignore file.
What do FROM, WORKDIR, COPY, RUN, CMD, and ENTRYPOINT do?
These instructions cover the common path from a base image to a runnable container, but no application needs every instruction. Use the reference documentation when an instruction has edge cases or platform-specific behavior.
| Instruction | Purpose | Typical Node.js example |
|---|---|---|
FROM |
Starts a stage from a base image. Every additional FROM starts another stage. |
FROM node:22-bookworm-slim |
WORKDIR |
Sets the working directory for subsequent instructions and the container process. | WORKDIR /app |
COPY |
Copies files from the build context, or from a named earlier stage, into the image. | COPY package*.json ./ |
RUN |
Executes a build-time command and records its result in an image layer. | RUN npm ci |
CMD |
Supplies the default command and arguments when a container starts. It is easy for a runtime command to override. | CMD ["node", "dist/server.js"] |
ENTRYPOINT |
Defines the executable a container is intended to run; command-line arguments are commonly appended to it. | ENTRYPOINT ["node"] |
Use the JSON (exec) form for a predictable process and argument handling, especially for a service. Keep the startup instruction focused on running the application; compiling, downloading dependencies, and other preparation belong in RUN steps during the build.
What is the smallest useful Dockerfile for a Node.js service?
A minimal single-stage file makes the instruction order visible. It is a useful starting point, but it commonly leaves compilers, development dependencies, and source files in the final image.
# syntax=docker/dockerfile:1
FROM node:22-bookworm-slim
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
CMD ["node", "dist/server.js"]
This example assumes a lockfile that makes npm ci appropriate and a build script that creates dist/server.js. If your project is plain JavaScript with no build step, remove RUN npm run build and point CMD at the actual entry file. If your package manager or output directory differs, change both the command and the copied paths.
Build it with docker build -t example-api:dev ., then start it with docker run --rm -p 3000:3000 example-api:dev if the service listens on port 3000. The image does not automatically publish a port; the -p option connects a host port to the container port at runtime.
How do instruction order, layers, and the build cache affect a Dockerfile?
Docker evaluates instructions from top to bottom, and earlier changes can invalidate work later in the file. A change to a frequently copied source file can therefore force dependency installation and compilation to run again if those steps precede it in the same invalidated chain. Docker explains this behavior in its guidance on build best practices and in the material on image layers and the build cache.
For a dependency-driven application, copy relatively stable manifests before frequently changing source files:
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY src ./src
COPY tsconfig.json ./
RUN npm run build
When only files under src change, the manifest copy and dependency installation can remain reusable if the corresponding cache entries are still available. This is an optimization, not a correctness rule: a build must still work from an empty cache, and the order must match what your build system actually requires. If a generated file is needed before dependency installation, copy or generate it at the point the build requires it rather than forcing a preferred cache pattern.
Also popular on Amazon
- 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
- Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
- Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
- HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
- What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
Use .dockerignore to keep unrelated material out of the context. Typical exclusions include node_modules, local build output, test reports, editor metadata, and credentials. Do not ignore a file that the Dockerfile needs; an excluded lockfile, for example, can make a supposedly reproducible install impossible.
The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →How should a production Dockerfile use multi-stage builds?
Use multiple stages when the build environment contains compilers, development dependencies, source code, or tooling that the running service does not need. Docker’s documentation states: “Multi-stage builds let you reduce the size of your final image, by creating a cleaner separation between the building of your image and the final output.” Each FROM starts a stage, and a later stage can copy selected output from an earlier one. See Docker’s multi-stage build guide.
Here is a two-stage version of the same Node.js service. The build stage installs all dependencies and compiles the application; the runtime stage installs production dependencies and receives only the compiled output.
# syntax=docker/dockerfile:1
FROM node:22-bookworm-slim AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM node:22-bookworm-slim AS runtime
WORKDIR /app
ENV NODE_ENV=production
COPY package*.json ./
RUN npm ci --omit=dev
COPY --from=build /app/dist ./dist
CMD ["node", "dist/server.js"]
The runtime stage is deliberately explicit: it gets the package manifests, production-only dependencies, and compiled files, not the build-stage toolchain. If your runtime needs static assets, migrations, certificates, or another generated directory, copy those outputs deliberately as well. A multi-stage build does not guess which files your application needs.
You can name a stage with AS build and copy from it with COPY --from=build. Naming stages is clearer than relying on numeric indexes and makes later reordering less error-prone. You can also target a particular stage during development with a builder command that selects the stage, while release builds should end at the intended runtime stage.
How do you choose and pin a base image?
Choose a base image by balancing maintenance, compatibility with your application and native modules, image size, and the update policy your team can actually operate. Docker recommends current official images where suitable. A version tag is convenient, but a publisher can rebuild or move that tag; a digest identifies a specific image identity. Docker discusses this trade-off in its best-practices documentation.
For development, a readable tag such as node:22-bookworm-slim is convenient. For a release workflow that must identify exactly which base image was used, resolve the tag to a digest and use the tag-plus-digest form in the Dockerfile. Do not copy an unverified digest from an example: obtain the digest from the image registry you trust and record how it is updated.
Pinning is not a substitute for maintenance. A digest can keep an old operating-system layer forever unless a scheduled update process, dependency review, or automated rebuild moves it forward. Conversely, an unpinned tag can change between two builds. Decide whether your priority for each environment is convenient updates, byte-for-byte identity, or a controlled combination, then document that decision.
How do BuildKit cache mounts improve builds without changing correctness?
BuildKit supports RUN --mount with bind, cache, tmpfs, secret, and SSH mount types. A cache mount stores package-manager or compiler cache data outside the committed image layer so later builds may avoid downloading or recompiling unchanged material. Docker warns that cache contents can be overwritten or garbage-collected, so the build must succeed when the cache is empty.
Windows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallCrashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minuteAlso popular on Amazon
- Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
- Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
- Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
- Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
- What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
For npm, an illustrative cache-aware step is:
# syntax=docker/dockerfile:1
RUN --mount=type=cache,target=/root/.npm npm ci
The command still needs the lockfile and network access required by a clean install. Never use a cache mount as the only place a required package, generated file, or credential exists. If a clean builder fails, fix the dependency declaration or build step rather than trying to preserve a cache indefinitely.
Cache behavior also depends on instruction inputs. Changing a package manifest should invalidate the install step; changing application source should not necessarily do so when the manifests are copied and installed first. Treat cache reuse as a performance improvement that can disappear without warning, not as part of your application’s correctness.
How do you use build secrets without putting credentials in an image?
BuildKit secret mounts let a build step read a credential without baking that credential into the resulting image or build cache. Ordinary ARG and ENV values are not a replacement for secret handling: values passed that way can become visible through image history, metadata, or layers.
For a private npm registry, mount a temporary configuration file only for the install step:
# syntax=docker/dockerfile:1
FROM node:22-bookworm-slim AS build
WORKDIR /app
COPY package*.json ./
RUN --mount=type=secret,id=npmrc,target=/root/.npmrc npm ci
COPY . .
RUN npm run build
Supply the secret when building, for example with docker build --secret id=npmrc,src=$HOME/.npmrc -t example-api:build .. The exact secret name, file path, and package-manager configuration depend on your registry. Keep runtime credentials and configuration in the deployment platform’s runtime secret mechanism; do not copy a local secret file into the image.
Review the Dockerfile and build logs for accidental disclosure. A secret mount protects the mounted value from being committed by the mount mechanism, but a command that prints the secret, writes it into an output file, or embeds it in generated artifacts can still disclose it.
What is the difference between CMD and ENTRYPOINT?
CMD supplies a default command that can be replaced when someone runs the container. ENTRYPOINT establishes the executable that the image is intended to run, while additional command-line arguments are commonly passed to it. Choose the simpler CMD form when the image is a service with one normal startup command; use an entrypoint when the executable role should remain fixed and arguments should be appended.
# Default service command; easy to override for diagnostics
CMD ["node", "dist/server.js"]
# Fixed executable with a default argument
ENTRYPOINT ["node"]
CMD ["dist/server.js"]
A shell-form command can behave differently with signal handling and argument expansion than the JSON form. Keep startup logic small and observable. If initialization requires several operations, put deterministic preparation in the build where possible, or use a carefully maintained entrypoint script whose behavior is documented and tested in CI.
How should Dockerfiles handle development and production dependencies?
Separate dependencies by purpose when your package manager supports it. Build stages often need development tools, type definitions, compilers, or test runners; the runtime stage generally needs only the dependencies required to execute the built application. Installing production dependencies in the runtime stage, as in npm ci --omit=dev, avoids copying the entire build environment.
Also popular on Amazon
- Portable and powerful USB-C HUB: BENFEI USB Type-C HUB, with super-soft and knot-free silicone woven design cable, meets most mobile office needs. Compact, lightweight, stylish, and powerful portable USB C Hub equipped with 1 x HDMI port, 1 x 100W charging, and 3 x USB ports. 18-month warranty, 24-hour response, to ensure you feel at ease when using our product.
- Design centered on comfort and reliability: Thanks to BENFEI's end-to-end in-house cable production capability, in-house PCBA and assembly capability, using the industry's most advanced silicone woven design and process, 20cm cable in length, no knots, super-soft, the HUB is easy to use in all scenarios: laptop, tablet, stand etc. Super-soft, 25000+ life cycles, to meet your daily carrying and office needs.
- 100W Charging: Support up to 90W USB C pass-through charging via Type-C port to keep your laptop powered. 10W is reserved for other interface operations. No data and video function on the Type-C port.
- 4K HDMI Display: The HDMI port supports media display at resolutions up to 4K 30Hz, keeping every incredible moment detailed and ultra vivid. Please note that the C port of the Host device needs to support video output.
- Transfer Files in Seconds: Transfer files and from your laptop at speeds up to 10 Gbps with USB A 3.2 port. Extra 2 USB A 2.0 ports are perfectly for your keyboards and mouse.
Do not remove a package merely because it is labeled “development” without checking the application. Some frameworks load packages at runtime, and some build outputs still require native libraries from the base image. The Dockerfile should express the actual runtime contract: executable files, shared libraries, static assets, certificates, and configuration paths.
Keep source maps, license files, and diagnostic tools according to your operational and legal needs. A smaller runtime stage can reduce what must be scanned and transferred, but size alone is not a complete production criterion; compatibility and debuggability matter too.
How do you build and test the same image workflow in CI?
Docker recommends building and testing images in continuous integration. Put the Dockerfile, context, lockfiles, and any required build configuration under source control. On pull requests or source changes, have CI build the image from a clean or appropriately isolated builder, run the application’s tests against that image, and publish only images that pass the required checks.
Quick wins for a faster PC:
Clear out junk files and repair common Windows errorsFree Scan →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Repair Windows errors before they cause bigger problemsFix Now →A generic workflow looks like this:
- Check out the exact commit being reviewed.
- Build the intended target, for example with
docker buildx build --tag registry.example.com/example-api:$GIT_SHA --load .when the runner needs a local image for tests. - Run unit, integration, or smoke tests against that image using the project’s documented commands.
- For a release, rebuild or promote the verified image according to your registry process and record the resulting image digest.
The registry hostname and CI syntax in that command are placeholders; use your organization’s platform and authentication method. The important property is that CI exercises the same Dockerfile and build arguments intended for release, rather than testing a different local setup. If you use cache exports to accelerate CI, preserve the clean-cache path as a required fallback.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.What commonly breaks, and how can you fix it?
“COPY failed: file not found”
Check the build context and .dockerignore. Docker can copy only files inside the context, and an ignored file is unavailable even if it exists on your workstation. Run the build from the directory that contains the intended project files, or change the context and paths deliberately.
The dependency install runs on every source change
Copy dependency manifests in an earlier step, install dependencies, and copy frequently changing source afterward. Confirm that the manifest files are stable and that the package manager is not reading a generated file that changes on every build. This improves cache reuse but cannot prevent invalidation when dependencies really change.
The final image contains compilers or test tools
Inspect the Dockerfile for a single-stage build or a broad COPY . . in the final stage. Move compilation into a named build stage and copy only the runtime outputs and production dependencies into the final stage.
Free tools Windows power users keep installed
One-click scans. No signup required.
A private dependency install leaks a token
Remove credentials from ARG, ENV, and copied files. Use a BuildKit secret mount for the one command that needs the credential, and check that the command does not print it or write it into generated output.
The image changed even though the Dockerfile did not
A mutable base-image tag or changing dependency source can produce a different result. If a fixed base identity is required, use a verified digest and maintain an explicit update process. Lock application dependencies with the package manager’s lockfile and rebuild through the same CI workflow.
Also popular on Amazon
- 【Read before You Buy】 Note: This adapter is USB 2.0 version and cannot transmit HDM, VGA, or other video signals. Nevertheless, they are fully capable of charging devices,duplicating files, and can be seamlessly integrated with USB-C earphones, wireless network adapters, and SD card adapters.
- 【Easy to Use and Safe】Thanks to modern manufacturing techniques, we've made these adapters sufficiently compact so that they can remain inserted in your device without noticeable protrusion or inconvenience. This means you don't have to constantly plug and unplug them, reducing the likelihood of wear and misalignment, and making them more convenient to carry around.
- 【Reliable Quality】Engineered for enhanced durability, durable aluminum alloy shell material,get excellent wear resistance and heat dissipation,the male USB C and female USB connectors & the male USB and female USB C connectors are designed to be plugged and unplugged up to 20000 times. Provides data transfer, device charging, memory space expansion, and additional computer peripherals.
- 【Think more for you】Do you need to connect a USB-C-enabled device to an odd device that only has USB-A ports? Then these USB-A male to USB-C female adapters are made for you.Simply insert the adapter into the USB-A port on the device, and you can instantly connect your USB-C device to the device that originally didn't have the correct connection port.
- 【Trusted xiwxi Quality and Service】As a responsible brand seller, you will receive xiwxi's 12-month Quality assurance and lifetime friendly customer service, you're not just buying a product,you're investing in peace of mind with all-round quality and exceptional customer service.
The container exits immediately
Inspect the effective command and its working directory. Verify that the file named by CMD or ENTRYPOINT exists in the final stage, that production dependencies were copied or installed there, and that the process is a long-running service rather than a one-time build command.
Single-stage or multi-stage: which Dockerfile design fits?
A single stage is often easiest to understand and can be suitable for a small script or a development image. A multi-stage design is usually better when building requires material that the running application does not need.
Do these 3 things before closing this tab:
1Clear out junk files and repair common Windows errors2Fix the driver behind crashes, sound loss and screen glitches3Repair Windows errors before they cause bigger problems| Decision axis | Single-stage design | Multi-stage design |
|---|---|---|
| Final contents | Build tools, source, and runtime files can remain together unless explicitly removed. | The runtime stage receives selected outputs, keeping build-only material out by construction. |
| Build-time simplicity | Fewer stages and straightforward paths. | More explicit boundaries and copy paths to maintain. |
| Cache strategy | Can still reuse layers when manifests and source are ordered well. | Allows separate caching for build dependencies and runtime dependencies. |
| Base-image policy | One base image may serve incompatible build and runtime needs. | Build and runtime bases can be chosen for their respective jobs. |
| Credential handling | Secrets used during build require care not to persist into the same final stage. | Secrets can be mounted only in the build stage, with no secret-bearing files copied forward. |
| CI release clarity | The tested image is simple to identify. | CI must build and test the intended final target, not an intermediate stage. |
What should a production Dockerfile checklist include?
- Context: The build context is intentional, and
.dockerignoreexcludes local caches, credentials, and irrelevant output. - Order: Stable dependency manifests are copied before frequently changing source where that matches the application’s build requirements.
- Correctness: The build succeeds with an empty cache and does not rely on cache contents.
- Stages: Compilers, test tools, and development dependencies stay in a build stage when the runtime does not need them.
- Base image: The image family and update policy are documented; releases use a digest when a specific base identity must be reproducible.
- Secrets: Build credentials use secret mounts and are not passed through ordinary arguments, environment variables, or copied files.
- Runtime: The final stage contains every executable, library, asset, and production dependency required by the startup command.
- Process:
CMDorENTRYPOINTuses the intended form and points to a real file in the final image. - Automation: CI builds and tests the same Dockerfile workflow used for release on source-control changes or pull requests.
- Maintenance: Base-image and dependency updates are scheduled rather than postponed indefinitely by pinning.
Where can you learn more after the Dockerfile basics?
The authoritative next steps are Docker’s Dockerfile reference, build best practices, and multi-stage build documentation. For a broader, intermediate-to-advanced treatment of Docker beyond Dockerfiles, the publisher listing for Docker Deep Dive, Fifth Edition describes a 2025 book covering fundamentals through production topics; it is optional further learning, not a prerequisite for this workflow.
Frequently Asked Questions
Can one Dockerfile produce both a development image and a production image?
Yes. Give development and runtime stages distinct names, then select the desired target during the build. Keep the production target explicit so CI does not accidentally publish an intermediate stage containing compilers, test tools, or source files.
Do I need BuildKit for a basic Dockerfile?
A basic file using ordinary FROM, COPY, and RUN instructions can work without advanced mounts. BuildKit is needed for features such as cache, secret, SSH, and other RUN --mount types, so enable it consistently wherever those features appear.
How often should a digest-pinned base image be refreshed?
There is no universal interval; tie refreshes to your security and maintenance policy. Schedule rebuilds or dependency-update work, review the new digest, run the same CI tests, and promote it only after the resulting image is accepted.
Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Scan for outdated or missing drivers - takes under a minute3Clear out junk files and repair common Windows errorsWhere should application secrets be supplied when the container starts?
Use the secret facility provided by your deployment platform or orchestrator at runtime, not a value baked into the image. Keep non-sensitive configuration separate from credentials and ensure the startup process reads the paths or environment contract documented for that platform.
Why does a Docker build work locally but fail in CI?
Local builds often have warm caches, untracked files, credentials, or a different build context. Reproduce CI with a clean context, verify every required file is committed and not ignored, and make network access, secret mounts, build arguments, and target stages explicit.

