Writing a Dockerfile
Guidelines for writing a Dockerfile
.¶
These are the main guidelines for writing Dockerfiles:
-
Building your
Dockerfile
should result a light docker image. It is recommended to have an image size of no more than 100Mb. This reduces build and shipping time and makes the build & deployment run faster. It is very important to invest time in this and try to reduce the image size as much as possible. -
Use an
ARG
in yourFROM
line. This will allow you to: -
Control the base image from the CI
- Update a project or all projects by updating a Variable.
Examples¶
DockerFile
ARG NGINX_VER
FROM nginx:${NGINX_VER}-alpine
In the .gitlab-ci.yml
file set the Base image tag you would like to use:
variables:
NGINX_VER: "1.17.8"
In the build stage pass it as a build argument with the build option --build-arg
:
build:
stage: build
script:
- docker login -u gitlab-ci-token -p $CI_JOB_TOKEN $CI_REGISTRY
- docker build --build-arg NGINX_VER=${NGINX_VER} -t $DEV_TAG .
- docker tag $DEV_TAG $LATEST_DEV
- docker push $DEV_TAG
- docker push $LATEST_DEV
tags:
- generic
except:
- tags
After installing packages in your Dockerfile
, clean it up.
RUN apk add --update \
python \
python-dev \
py-pip \
build-base \
&& pip install virtualenv \
&& rm -rf /var/cache/apk/*
Depending on your FROM
image it is also possible to run apk add without cache.
RUN apk --no-cache add nginx
This avoids the need to use
--update and remove /var/cache/apk/*
Using multi-stage builds¶
Below there are two examples of the same build
-
The 1st one is hard to maintain & read.
-
The second example is readable and allows you to build the image with 2 stages, copying the artifacts of the 1st stage to the 2nd build stage.
-
This is all done with a single
Dockerfile
.
DO NOT USE THIS !
This is not good practice.
FROM golang:1.7.3
WORKDIR /go/src/github.com/alexellis/href-counter/
COPY app.go .
RUN go get -d -v golang.org/x/net/html \
&& CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o app .
USE THIS
This is better way to create the final image.
FROM golang:1.7.3
WORKDIR /go/src/github.com/alexellis/href-counter/
RUN go get -d -v golang.org/x/net/html
COPY app.go .
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o app .
FROM alpine:latest
RUN apk --no-cache add ca-certificates
WORKDIR /root/
COPY --from=0 /go/src/github.com/alexellis/href-counter/app .
CMD ["./app"]
There is great documentation at docker website.