How to Use Docker Credentials in Jenkins for Secure Image Access
In Jenkins, you use
Docker credentials by adding them in Jenkins Credentials Manager and referencing them in your pipeline with docker.withRegistry() or withCredentials(). This securely authenticates Jenkins to Docker registries for pulling or pushing images.Syntax
To use Docker credentials in Jenkins pipelines, you typically use the docker.withRegistry() method or the withCredentials() step. The key parts are:
credentialsId: The ID of the Docker credentials stored in Jenkins.registryUrl: The Docker registry URL (e.g.,https://index.docker.io/v1/for Docker Hub).docker: The Docker pipeline object to run commands inside the authenticated context.
groovy
docker.withRegistry('https://index.docker.io/v1/', 'my-docker-credentials') { // Docker commands here }
Example
This example shows a Jenkins pipeline that logs into Docker Hub using stored credentials, builds a Docker image, and pushes it to the registry.
groovy
pipeline {
agent any
stages {
stage('Build and Push Docker Image') {
steps {
script {
docker.withRegistry('https://index.docker.io/v1/', 'docker-hub-credentials') {
def appImage = docker.build('myapp:latest')
appImage.push()
}
}
}
}
}
}Output
Authenticating with Docker registry...
Building Docker image 'myapp:latest'...
Pushing image to Docker Hub...
Push successful.
Common Pitfalls
Common mistakes when using Docker credentials in Jenkins include:
- Not adding Docker credentials in Jenkins Credentials Manager before referencing them.
- Using the wrong
credentialsIdor registry URL. - Forgetting to wrap Docker commands inside
docker.withRegistry(), causing authentication failures. - Using plain text passwords or exposing credentials in logs.
Always use Jenkins credentials and pipeline steps to keep secrets safe.
groovy
/* Wrong way: Using docker commands without authentication */ sh 'docker push myapp:latest' /* Right way: Using docker.withRegistry with credentials */ docker.withRegistry('https://index.docker.io/v1/', 'docker-hub-credentials') { def appImage = docker.build('myapp:latest') appImage.push() }
Quick Reference
Summary tips for using Docker credentials in Jenkins:
- Add Docker credentials in Jenkins Credentials Manager (type: Username with password).
- Use
docker.withRegistry(registryUrl, credentialsId)to authenticate in pipelines. - Wrap all Docker build and push commands inside the
withRegistryblock. - Never hardcode credentials in pipeline scripts.
Key Takeaways
Store Docker credentials securely in Jenkins Credentials Manager before use.
Use docker.withRegistry() in pipelines to authenticate Docker commands.
Wrap build and push commands inside the withRegistry block for authentication.
Avoid exposing credentials in logs or pipeline code.
Use correct registry URL and credentialsId to prevent authentication errors.