ruk·si

🐳 Dockerfiles

Updated at 2020-05-05 16:35

Dockerfiles are build instructions for Docker images.

You usually have Dockerfile at the root of your project. And you have a simple script or guidelines to build the image in a standardized way. This is the case if the project has only have one Docker image to maintain.

docker build owner-name/image-name:20200505 .
# or
make
# or
python build.py --push

Make sure you have apt-get update and apt-get install in the same RUN. Otherwise it will cache the repository update and you can get some funky behaviour between build computers. Post-install cleaning is optional but recommended.

RUN apt-get update --fix-missing && \
    apt-get install -y --no-install-recommends \
        gcc \
        make \
        && \
    apt-get clean && \
    apt-get autoremove && \
    rm -rf /var/lib/apt/lists/*

Install dependencies separately for quick builds. If you simply include a whole directory, the layer must be rebuild after any of the directory files change.

# BAD
COPY ./app/ /home/app/
WORKDIR /home/app/
RUN pip install -r requirements.txt

# GOOD
COPY ./app/requirements.txt /home/app/
WORKDIR /home/app/
RUN pip install -r requirements.txt
COPY ./app/ /home/app/

Use COPY over ADD. Use COPY instead as ADD has subtle magic that can cause bugs.

ADD example.tar.gz /add     # will unarchive the tar
COPY example.tar.gz /copy   # will copy the actual tar

Always use specific base image versions.

# BAD
FROM node:latest

# GOOD
FROM node:6.2.1

Declared ENVs as late as possible. They will bust the cache.

ENV LANG=C.UTF-8 LC_ALL=C.UTF-8

Use build images if your building requires different dependencies from running.

FROM node:12.16 as frontend-build
WORKDIR /home/app/
COPY package.json yarn.lock /home/app/
RUN yarn && rm -rf $(yarn cache dir)
COPY . /home/app
RUN env NODE_ENV=production yarn build

# ...
COPY --from=frontend-build /home/app/static /home/app/static

Sources