Kubernetes for Developers
上QQ阅读APP看书,第一时间看更新

Practical notes for building container images

The following are suggestions and practical advice for maintaining your container images:

  • Keep a Dockerfile in your source repository. If your application source is by itself in a Git repository, then including a Dockerfile in the repository along with it makes a great deal of sense. You can reference files to COPY or ADD from the relative directory of where your source is located. It’s not uncommon to see a Dockerfile in the root of a repository, or if you're working from a monorepo with many projects, consider a Docker directory in the same directory as your project’s source code:
    • If you want to take advantage of an automatic Docker build on Docker Hub, Quay, or another container repository, the automated system expects the Dockerfile to be in the root of your Git repository.
  • Maintain a separate script (if needed) for creating the container image. Or more specifically, don’t mix the process of creating your container image with code generation, compilation, testing, or validation. This keeps a clear separation of concerns from development tasks that you may need, depending on your language and framework. This will allow you to include it when and where you want to in an automation pipeline.
  • It will be very tempting to add in additional tools to your base image to enable debugging, support new or additional diagnostic work, and so on. Make an explicit and conscious choice of what additional tooling you will (and won’t) include within the image. I advise minimal additional tools, not just because they cause the image to be larger, but often the same tools that are so effective at debugging present an option for easier exploitation from hackers:
    • If you find you must add debugging tools into your image, consider making a second Dockerfile in a subdirectory that adds to the first and only includes the debugging tools you want to add. If you do this, I recommend you add a name -debug to the name of the image to make it clear that the image has the additional tooling installed.
  • When you build your container image, build it with production usage in mind, and as a default. With containers, this is often represented with default values for environment variables that are made available in the container. In general, try not to include the dependencies needed for unit testing, development tasks, and so on in your container image:
    • In the case of Node.js, use the environment variable ENV=PROD, so that npm doesn’t include development dependencies, or explicitly strip them away with a command line npm install —production.
  • Treat the entire container you create as a read-only filesystem after you’ve created it. If you want to have some place to write local files, identify that location explicitly and set up a volume in your container for it.