Hacker News new | ask | show | jobs
by lipanski 2071 days ago
One of the most common mistakes I see is not using a .dockerignore file or, better said, relying on .gitignore when calling `COPY` on entire directories. Without a .dockerignore file in place, you could be copying over your local .env files and other unwanted things into the final image.

On top of that, you might also want to add `.git/` to your .dockerignore file, as it could significantly reduce the size of your image when calling `COPY`.

A more subtle issue I've noticed is the fact that `COPY` operations don't honour the user set when calling `USER`. The `COPY` command has its own `--chown` argument, which needs to be set if you'd like to override the default user (which is root or a root-enabled user in most cases).

I wrote up a similar article a while back, though it's focused on general best practices: https://lipanski.com/posts/dockerfile-ruby-best-practices

1 comments

Better yet, only COPY the actually needed needed files instead of the whole working directory. That way, there's no need for a `.dockerignore`.
While this is a good idea, having a `.dockerignore` reduces how much Docker has to load into the build context. For projects with large histories, the `.git` directory itself can be rather large. Add to that directories that hold build artifacts, documentation, and you are unnecessarily increasing the time it takes to start the build process.
Wondering why you think this is better. Not sure the trade off of a messy dockerfile and/or adding a bunch of layers (possibly bloating the image size) is worth the trade off if the concern is just about forgetting to update the dockerignore. The same could be said about gitignore.
Not the person you replied to, but personally, I like having control over what exactly gets into the final image, and (IME) have found that devs aren't great about remembering to update .dockerignore files. Re: extra layers, if you use multi-stage builds to separate the builder and final app images, you can avoid that.
It's nice to know what files you need to build the image. Sort of like importing libraries at the top of a source code file.
I'm not sure that's always practical. Consider the average Rails or Symfony app - you'd have to include quite a few files (even if you add entire directories at a time).