SyntaxStudy
Sign Up
Docker ARG, ENV, and HEALTHCHECK
Docker Beginner 1 min read

ARG, ENV, and HEALTHCHECK

ARG declares a build-time variable passable via --build-arg. Unlike ENV, ARG values are not present in the running container (though they are visible in docker history — never use them for secrets). ARG is useful for parameterising the base image version or application version number in a way that is overridable per build without editing the Dockerfile. ENV sets environment variables that persist in the running container and are visible to the application. They can reference previously defined ENV or ARG values. Setting NODE_ENV=production as an ENV instruction ensures the application always runs in production mode unless overridden at container start with docker run -e NODE_ENV=development. The HEALTHCHECK instruction tells Docker how to test whether the container is functioning correctly. Docker runs the check command at the specified interval and marks the container healthy or unhealthy accordingly. Container orchestrators like Swarm and Kubernetes use this status to route traffic and restart unhealthy containers automatically.
Example
# ARG before FROM affects the FROM line only
ARG NODE_VERSION=20
FROM node:${NODE_VERSION}-alpine

# ARG after FROM is scoped to this build stage
ARG APP_VERSION=dev
ARG BUILD_DATE

WORKDIR /app

# ENV persists in the running container
ENV NODE_ENV=production \
    PORT=3000 \
    APP_VERSION=${APP_VERSION}

# OCI standard labels
LABEL org.opencontainers.image.version="${APP_VERSION}" \
      org.opencontainers.image.created="${BUILD_DATE}" \
      org.opencontainers.image.source="https://github.com/myorg/myapp"

COPY package.json package-lock.json ./
RUN npm ci --omit=dev
COPY src/ ./src/

EXPOSE 3000

# HEALTHCHECK: test every 30s, timeout 5s, 3 retries
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
    CMD wget -qO- http://localhost:3000/health || exit 1

CMD ["node", "src/server.js"]

# Build:
# docker build \
#   --build-arg APP_VERSION=2.1.0 \
#   --build-arg BUILD_DATE=$(date -u +%Y-%m-%dT%H:%M:%SZ) \
#   -t myapp:2.1.0 .