KnowledgeHub
VI EN

Bài viết

Dockerfile: FROM, RUN, COPY, CMD, ENTRYPOINT

The five foundational Dockerfile instructions — get them right and your images stay small, fast, and correct.

28/08/2026 · 0 phút đọc · 14 lượt xem

FROM — pick a base image

Every Dockerfile starts with FROM. Pick small and appropriate: alpine for minimal, slim for balance.

dockerfile
FROM ruby:3.4-slim

RUN — commands at build time

RUN executes a command and creates a new layer. Chain related commands with && to keep layers few:

dockerfile
RUN apt-get update && apt-get install -y --no-install-recommends libpq-dev \
    && rm -rf /var/lib/apt/lists/*

COPY — files into the image

COPY moves files from the build context into the image. Use .dockerignore to exclude log/, tmp/, .git — a smaller context builds faster.

CMD vs ENTRYPOINT — commands at run time

  • ENTRYPOINT is the main command, hard to override (e.g. rails server)
  • CMD is the default argument to ENTRYPOINT, easy to override with docker run
dockerfile
ENTRYPOINT ["./bin/rails"]
CMD ["server", "-p", "3000", "-b", "0.0.0.0"]

docker run app console replaces CMD with console while keeping ENTRYPOINT — exactly what you want for a Rails app.

Layer order decides build speed

Put rarely-changing layers first (packages, bundle install), fast-changing code last. Docker caches layers in order — changing one line of code won't rebuild everything if earlier layers are cached.