Docker in CI (build and push images)
Topic: Containers core
Summary
In CI, build Docker images with docker build, tag with registry and version, and push with docker push. Use a registry (Docker Hub, ECR, GCR) and authenticate with a token or role. Use this when automating image builds in a pipeline.
Intent: How-to
Quick answer
- Build: docker build -t registry/myapp:${CI_COMMIT_SHA} . (or tag with branch/tag). Push: docker login (with token or env); docker push registry/myapp:${CI_COMMIT_SHA}. Use a dedicated CI user or role with minimal push rights.
- Cache: use docker buildx or --cache-from to reuse layers from previous build or from registry. In GitHub Actions: cache Docker layers; in GitLab CI: use docker layer caching. Reduces build time.
- Multi-arch: use buildx to build for amd64 and arm64 if you need both. Scan image after build (trivy, scout) and fail pipeline on critical vulnerabilities. Do not use latest tag for production; use digest or version tag.
Prerequisites
Steps
-
Authenticate to registry
echo $REGISTRY_TOKEN | docker login -u ci --password-stdin registry.example.com. Or use AWS ECR: aws ecr get-login-password | docker login --username AWS --password-stdin account.dkr.ecr.region.amazonaws.com.
-
Build and tag
docker build -t registry.example.com/myapp:$VERSION . Use commit SHA, tag, or build number as VERSION. Tag also as latest only for dev if needed.
-
Push and cache
docker push registry.example.com/myapp:$VERSION. For cache: docker build --cache-from registry.example.com/myapp:latest -t registry.example.com/myapp:$VERSION .; then push.
-
Scan and optional multi-arch
Run trivy or docker scout on the image; fail if critical/high. For multi-arch: docker buildx build --platform linux/amd64,linux/arm64 -t registry/myapp:$VERSION --push .
Summary
In CI, log in to the registry, build with a version tag, push the image, and optionally use cache and multi-arch. Use this to automate image build and push in a pipeline.
Prerequisites
Steps
Step 1: Authenticate to registry
Log in with a CI token or cloud credential (e.g. ECR get-login-password).
Step 2: Build and tag
Build with a version tag (SHA, tag, or build number); avoid mutable latest for production.
Step 3: Push and cache
Push to the registry; use —cache-from to speed up subsequent builds.
Step 4: Scan and optional multi-arch
Scan the image and fail on critical issues; use buildx for multi-arch if required.
Verification
- Pipeline builds and pushes the image; image is available in the registry with the expected tag; scan passes or is enforced.
Troubleshooting
Login failed — Check token or IAM role; ensure registry URL is correct. Push denied — CI user needs push permission; check namespace and repo name.