Module 11 Lesson 3: CI/CD Integration with Docker
Automate everything. Learn how to use Docker in your GitHub Actions or GitLab CI pipelines to build, test, and push images automatically on every commit.
Module 11 Lesson 3: CI/CD Integration with Docker
In a professional environment, developers don't run docker build and docker push manually. A CI/CD pipeline (like GitHub Actions, GitLab CI, or Jenkins) does it for them.
1. The Automated Workflow
Every time you "Push" code to GitHub:
- Trigger: GitHub sees the new code.
- Checkout: A virtual machine starts and downloads your code.
- Build: The VM runs
docker build. - Test: The VM runs
docker runto execute your tests inside the container. - Push: If tests pass, the VM runs
docker pushto send the image to the registry.
2. Example: GitHub Actions Workflow
Create a file at .github/workflows/docker-build.yml:
name: Docker Build & Push
on:
push:
branches: [ "main" ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Login to Docker Hub
run: echo "${{ secrets.DOCKER_PASSWORD }}" | docker login -u "${{ secrets.DOCKER_USER }}" --password-stdin
- name: Build and push
run: |
docker build -t myuser/my-app:${{ github.sha }} .
docker push myuser/my-app:${{ github.sha }}
3. Using Git Commit Hashes as Tags
Notice ${ github.sha }`` in the example above.
- This is the long random string that identifies your specific commit.
- Why use it?: It creates an Audit Trail. You know exactly which line of code created which image in production.
- If
v1.2is broken, you look at the registry and see the SHA tag, which tells you exactly where the bug was introduced.
4. The "Build Once, Deploy Many" Principle
You should build your Docker image only once in the CI stage.
- Use that same exact image for QA, Staging, and Production.
- Don't rebuild the image for each environment; only change the Environment Variables (Module 4) to point to different databases.
Exercise: The Pipeline Plan
- Think about a project you have on GitHub.
- If you wanted to add a "Vulnerability Scan" (Module 7) to this pipeline, where would it go? (Before or After the
push?) - Why is it better to store your Docker password in "GitHub Secrets" rather than typing it directly into the YAML file?
- Research: What is the "Docker Layer Cache" in GitHub Actions, and how does it save you money/time?
Summary
CI/CD turns Docker from a "Developer tool" into a "Production engine." By automating the build and push process, you eliminate human error and ensure that every piece of code is tested and containerized before it ever reaches a user.
Next Lesson: Quality control: Automated builds and testing.