Docker Best Practices

Docker optimization tips

Image Size

FROM alpine # use minimal base images
RUN apt-get clean && rm -rf /var/lib/apt/lists/* # clean up in same layer
.dockerignore # exclude unnecessary files

Layer Optimization

RUN apt-get update && apt-get install -y pkg # combine commands
COPY package.json . # copy dependencies first
RUN npm install # then install
COPY . . # copy source code last

Security

USER node # run as non-root user
RUN chown -R node:node /app # set proper permissions
# scan images: docker scan image

Multi-stage Builds

FROM node:16 AS builder # build stage
FROM node:16-alpine # production stage
COPY --from=builder /app /app # copy from build stage

Health Checks

HEALTHCHECK CMD curl -f http://localhost/ || exit 1 # add health check

Labels and Metadata

LABEL version=1.0 # version label
LABEL description=My App # description label