logo

Docker Build Cheatsheet

Dockerfile

CMD vs ENTRYPOINT

Both CMD and ENTRYPOINT instructions define what command gets executed when running a container. There are few rules that describe their co-operation.

  • Dockerfile should specify at least one of CMD or ENTRYPOINT commands.
  • ENTRYPOINT should be defined when using the container as an executable.
  • CMD should be used as a way of defining default arguments for an ENTRYPOINT command or for executing an ad-hoc command in a container.
  • CMD will be overridden when running the container with alternative arguments.

FROM

  • Node LTS version: FROM node:lts-slim

Example: Containerize a Node app

Use this Dockerfile template:

# node
FROM node:12-slim

# the path inside the container
WORKDIR /usr/src/app

# copy the package.json and package-lock.json, and install dependencies
COPY package*.json ./
RUN npm install

# copy all the source code
COPY . .

# port
EXPOSE 8080

# run the command inside the container
CMD [ "node", "app.js" ]

And add a .dockerignore file:

Dockerfile
.dockerignore
node_modules
npm-debug.log

What is || : &&

|| : && creates a conditional execution flow:

  • The command before || is executed.
  • If it succeeds, the || : part is skipped, and the command after && is executed.
  • If it fails, the || : part is executed (doing nothing), and then the command after && is executed regardless.

This pattern is often used to ensure that subsequent commands in a RUN instruction are always executed, even if a previous command fails. This is useful for tasks like cleaning up or setting up configurations that should happen regardless of earlier failures.

RUN apt-get update || : && apt-get install -y --no-install-recommends some-package

Build

docker can build a docker image or an OCI image:

docker buildx build --output type=oci .
docker buildx build --output type=docker .

docker build vs docker buildx build

2 Docker build commands:

  • docker build: the legacy builder; always takes a copy of the local filesystem.
  • docker buildx build: Extended build capabilities with BuildKit.
    • BuildKit has been integrated to docker build since Docker 18.09.
    • BuildKit only requests the resources that the build needs, when they're needed.
    • A drop-in replacement for the legacy build.
    • In newer versions of Docker Desktop and Docker Engine, you're using Buildx by default when you invoke the docker build command.

BuildKit, or buildkitd, is the daemon process that executes the build workloads. A build execution starts with the invocation of a docker build command. Buildx interprets your build command and sends a build request to the BuildKit backend.

# List builder (will show BUILDKIT version)
$ docker buildx ls

# Inspect builder
$ docker buildx inspect $BUILD_NAME
$ docker buildx inspect default