Fix that Container — tips on writing dockerfile
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.
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.
- 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.
- 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 –
RUN apt-get update && apt-get install -y curl \
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
3. Use a init process.
- 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
pm2 image for running the final app. Node image is 118 mb compared to 800mb Ubuntu image.
5. Use an appropriate base image
You do not need to start with ubuntu and install your packages everytime. Consider using
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.