Fix that Container — tips on writing dockerfile

Shubham Sharma
2 min readDec 17, 2017

--

Started using Docker yet? Here are some tips on writing dockerfile for your application.
While may be obvious to docker experts, these tips might help you avoid common issues.

1. Minimize the number of layers.

FROM ubuntu:16.04
RUN apt-get update
RUN apt-get install node
RUN apt-get install npm
RUN apt-get install curl

Apt-get would be the most used command in all docker files command. While the above dockerfile looks fine, it has a couple of issues.

  1. apt-get update and apt-get install’s are on different lines, which would lead to caching of apt-get update command. Read more on docker build cache.
  2. Each of the RUN statements creates a layer in docker image, this leads to a bulkier image, try clubbing RUN commands logically.

A Better build would start like –

FROM ubuntu:16.04
RUN apt-get update && apt-get install -y curl \
node\
npm

2. Use .dockerignore file

While building dockerfile docker client sends all of the working directory content to docker daemon. You would have see something like this –
Sending build context to Docker daemon 131.5MB
To avoid high build times, ignore all content not useful in final image by using .dockerignore file.

3. Use a init process.

There has been a lot of discussion here , here about what should be pid 1 inside docker container.
Cutting the story short

  • Either use a full blown init system like supervisor or a tiny one like tini
  • If you are fine with some hacks you can probably get away with using bash with proper signal handling, see sample.

4. Use Multistage-builds

With multistage builds, you can isolate the build dependencies from production environment.

For eg — You can use a node image for npm build and then switch to a nginx or pm2 image for running the final app. Node image is 118 mb compared to 800mb Ubuntu image.

Read more.

5. Use an appropriate base image

You do not need to start with ubuntu and install your packages everytime. Consider using node:latest or openjdk:1.8, if you need some dependencies for build step consider using multi stage builds.

Originally published at gabber12.me on December 17, 2017.

--

--