Using SSH Mounts in Docker Builds
docker build
, for example to install private Git dependencies via SSH, without baking any keys into your image.If you’ve ever needed to install a private Git dependency during a Docker build, such as a package in your package.json
like:
json code snippet start
"dependencies": {
"my-private-module": "git+ssh://git@github.com/your-org/my-private-module.git"
}
json code snippet end
You might have run into authentication issues or resorted to insecure workarounds like copying SSH keys into the image.
Instead, Docker SSH mounts offer a secure and temporary way to use your existing local SSH agent during image builds. This means your private SSH keys stay on your host machine and are never stored in the image.
Enabling SSH mounts in a Dockerfile
In your Dockerfile, you might write:
Dockerfile code snippet start
FROM node:22
WORKDIR /app
COPY package.json package-lock.json ./
# Use your local SSH credentials to install private dependencies
RUN --mount=type=ssh npm ci
COPY . .
CMD ["node", "index.js"]
Dockerfile code snippet end
Building the Image with SSH access
To build this image and allow the SSH mount, use the following command:
shell code snippet start
docker build --ssh default -t your-image-name .
shell code snippet end
This will give the container access to your local SSH agent only during build time, ensuring your credentials remain secure and are not embedded in the final image.