How to Push Docker Image in Jenkins: Step-by-Step Guide
To push a Docker image in Jenkins, use a Jenkins pipeline that builds the Docker image with
docker build, then logs in to your Docker registry using docker login, and finally pushes the image with docker push. Make sure Jenkins has Docker installed and credentials configured for the registry.Syntax
The basic commands to push a Docker image in Jenkins pipeline are:
docker build -t <image-name>:<tag> .- Builds the Docker image from the Dockerfile.docker login -u <username> -p <password> <registry-url>- Authenticates Jenkins to the Docker registry.docker push <image-name>:<tag>- Pushes the built image to the registry.
These commands are usually run inside a Jenkins pipeline script or a shell step.
bash
docker build -t <image-name>:<tag> .
docker login -u <username> -p <password> <registry-url>
docker push <image-name>:<tag>Example
This Jenkins pipeline example builds a Docker image, logs into Docker Hub, and pushes the image to your Docker Hub repository.
groovy
pipeline {
agent any
environment {
DOCKERHUB_CREDENTIALS = credentials('dockerhub-creds')
IMAGE_NAME = 'yourdockerhubusername/myapp'
IMAGE_TAG = 'latest'
}
stages {
stage('Build Image') {
steps {
script {
sh "docker build -t ${IMAGE_NAME}:${IMAGE_TAG} ."
}
}
}
stage('Login to Docker Hub') {
steps {
script {
sh "echo ${DOCKERHUB_CREDENTIALS_PSW} | docker login -u ${DOCKERHUB_CREDENTIALS_USR} --password-stdin"
}
}
}
stage('Push Image') {
steps {
script {
sh "docker push ${IMAGE_NAME}:${IMAGE_TAG}"
}
}
}
}
}Output
Sending build context to Docker daemon 2.048kB
Step 1/5 : FROM alpine
---> a24bb4013296
...
Login Succeeded
The push refers to repository [docker.io/yourdockerhubusername/myapp]
...
latest: digest: sha256:abc123 size: 1234
Common Pitfalls
- Missing Docker installation: Jenkins agent must have Docker installed and running.
- Incorrect credentials: Use Jenkins credentials plugin to securely store and access Docker registry login info.
- Not using
--password-stdin: Avoid passing passwords directly in commands for security. - Tagging errors: Always tag images properly before pushing to avoid overwriting or pushing wrong images.
bash
Wrong way: sh "docker login -u user -p password" Right way: sh "echo $PASSWORD | docker login -u $USERNAME --password-stdin"
Quick Reference
Remember these key steps when pushing Docker images in Jenkins:
- Build image with
docker build - Login securely with
docker login --password-stdin - Push image with
docker push - Use Jenkins credentials plugin for secrets
- Ensure Docker is installed on Jenkins agents
Key Takeaways
Use Jenkins pipeline stages to build, login, and push Docker images step-by-step.
Store Docker registry credentials securely using Jenkins credentials plugin.
Always use 'docker login' with '--password-stdin' for better security.
Ensure Docker is installed and accessible on Jenkins build agents.
Tag your Docker images clearly before pushing to avoid confusion.