Docker image creation and optimization Example 1

Create a new image.
First create a folder for project named docker-bp:

$ mkdir docker-bp
$ cd docker-bp
Create files:
$ cat custom.conf
server {
  listen 80;
  server_name docker.pctags.com;
  location / {
    root /opt/app;
    index index.html index.htm;
  }
  location /test {
    return 200 '$hostname\n';
  }
}
$ mkdir app
$ cat app/index.html 
<h1>Hello from Nginx!</h1>
$ cat Dockerfile 
FROM debian
COPY . /opt
RUN apt-get update
RUN apt-get install -y nginx
COPY custom.conf /etc/nginx/conf.d/
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
Build the image:
$ docker build -t docker-bp .
Check the size of Docker image docker-bp at this step:
$ docker images | grep docker-bp
196MB

Optimize – step 2:
Make RUN to execute in a single command
Remove apt-get cache
$ cat Dockerfile
FROM debian
COPY . /opt
RUN apt-get update && apt-get install -y \
    nginx \
    && rm -rf /var/lib/apt/lists/*
COPY custom.conf /etc/nginx/conf.d/
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
Build the image:
$ docker build -t docker-bp .
Check the size of Docker image docker-bp at this step:
$ docker images | grep docker-bp
178MB

Optimize – step 3:
Add .dockerignore
$ cat .dockerignore
.git
Dockerfile
Build the image:
docker build -t docker-bp .
Check the size of Docker image docker-bp at this step:
$ docker images | grep docker-bp
175MB

Optimize – step 4:
Change base image to minimal Linux – Alpine
$ cat Dockerfile 
FROM alpine
COPY . /opt
RUN apk add --no-cache nginx && mkdir -p /run/nginx
COPY custom.conf /etc/nginx/conf.d/
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
Build the image:
$ docker build -t docker-bp .
Check the size of Docker image docker-bp at this step:
$ docker images | grep docker-bp
6.9MB

Optimize step 5 – change the order of instructions to make effective use of cache (creating Docker layers):
$ cat Dockerfile 
FROM alpine
RUN apk add --no-cache nginx && mkdir -p /run/nginx
EXPOSE 80
COPY custom.conf /etc/nginx/conf.d/
COPY . /opt
CMD ["nginx", "-g", "daemon off;"]
Now, change something in code in app/index.html and rebuild image. You’ll notice a faster rebuild, because Docker used cache.

Optimize step 6 – use image tags and versions for packages to make sure that your image will always work:
$ cat Dockerfile 
FROM alpine:3.11.5
ENV NGINX_VERSION 1.16.1-r6
RUN apk add --no-cache --repository http://dl-cdn.alpinelinux.org/alpine/v3.11/main nginx=${NGINX_VERSION} \
    && mkdir -p /run/nginx
EXPOSE 80
COPY custom.conf /etc/nginx/conf.d/
COPY . /opt
CMD ["nginx", "-g", "daemon off;"]