Docker best practices
- Use a least privileged user.
- Use multi-stage builds.
- Scan for security vulnerabilities.
- Use smaller size official images.
- Use caching.
- Use relevant tagging scheme for images rather than using the default tag.
- Run containers as non-root users.
- Use distroless images.
- Multistage Builds
Creating a User in docker image to handle permission
By default docker uses root user permission
ARG UID=1000 ARG GID=1000 RUN groupadd -r --gid $GID user && useradd -r --uid $UID -g user user
Using the created user
USER user
Docker Commands
Docker inspect
docker inspect {{ image name }}
Docker remove container
docker image rm
Docker remove image
docker image rmi
Docker Format
Docker format can be used with any command to format it output.
docker --format '{{ Tag }}'
Docker Filter
Docker filter
docker --filter
Dockerfile
Docker file to run dev env
FROM node # Create app directory WORKDIR /app # Copy dep COPY package.json pnpm-lock.yaml ./ RUN pnpm install COPY .. ENTRYPOINT ["pnpm", "run"] CMD ["dev"]
Docker Volumes
Docker volumes are a way to manage and persist data in Docker containers. A volume is a directory or file that exists outside of the container's file system and can be shared by multiple containers. This allows for data to persist between container runs, making it easy to manage and backup data.
Persistent Storage
Volume Plugins
Filesystem Mount
To create a host-mounted volume, you can use the
-v
flag when running a container, followed by the path to the volume on the host system.docker run -v /path/on/host:/path/in/container myimage
TMPS Mount
It is used to store sensitive data in memory.
Named
Anonymous volumes
To create an anonymous volume, you can use the
-v
flag followed by just the path in the container.docker run -v /path/in/container myimage
This will create an anonymous volume at the path
/path/in/container
in the container.You can also manage volumes using the
docker volume
command, which allows you to create, list, inspect, and remove volumes.Bind Mount
It mounts the host’s file system to a docker container.