dockerfile agent. This approach is useful when the base image from Docker Hub lacks command-line tools or libraries required by your pipeline steps.
Problem overview
- The example uses
node:18-alpineas the agent image, which includes Node and npm but does not include thecowsayCLI. - Running
cowsayin that container fails because the binary is missing.
node:18-alpine as an agent and run node, npm, and cowsay inside the container:
- The
node:18-alpineimage includes Node.js and npm but not thecowsaypackage, so invokingcowsayfails. - To fix this, create a custom image that extends
node:18-alpineand installs the missing CLI(s).
Dockerfile.cowsay) in your repository workspace with the following contents. Because the base image uses Alpine Linux, use apk to install required packages, then clone and install cowsay from its GitHub repo:
dockerfile agent
Update the pipeline stage to use the dockerfile agent so Jenkins will build the image from the Dockerfile in the workspace and run the stage inside a container created from that image.
Note: This is
dockerfile (not docker). The dockerfile agent builds the image from the specified Dockerfile in the workspace, then runs your steps inside a container created from that image.Dockerfile.cowsay):
- Read
Dockerfile.cowsayfrom the workspace. - Build a Docker image (you’ll see a
docker build -t ... -f Dockerfile.cowsay .invocation in the logs). - Start a container from the built image and run your
shsteps inside it.
cowsay executes as expected. Example final output:
Troubleshooting and important notes
Warning: The Jenkins node that builds the Docker image must have Docker (or a compatible container runtime) available and properly configured for the Jenkins user. If Docker is not accessible from the agent, the
docker build step will fail. Ensure the agent has permission to run Docker (or use a dedicated Docker-in-Docker or privileged agent).- If builds are slow, consider pushing a pre-built image to a registry and using
agent { docker { image 'your-registry/your-image:tag' } }in production. - For complex images, include a small changelog or versioning tag in the Dockerfile to help with caching and reproducible builds.
- Monitor Jenkins logs to confirm the
docker buildand container start steps.
- Use a Dockerfile when the base image lacks required CLI tools or libraries.
- Add the Dockerfile to your repository workspace (e.g.,
Dockerfile.cowsay). - Configure the declarative pipeline with
agent { dockerfile { filename 'Dockerfile.cowsay' } }. - Verify Jenkins build logs show
docker buildand thatcowsay(or other tools) run successfully inside the container.