Docker CI/CD
Integrating Docker with a CI/CD pipeline to automate build, test, and deployment.
GitHub Actions
# .github/workflows/docker.yml
name: Docker CI/CD
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Build image
run: docker build -t myapp:${{ github.sha }} .
- name: Run tests
run: docker run myapp:${{ github.sha }} npm test
deploy:
needs: build
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Login to Docker Hub
uses: docker/login-action@v2
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_TOKEN }}
- name: Build and push
uses: docker/build-push-action@v4
with:
push: true
tags: username/myapp:${{ github.sha }}
GitLab CI
# .gitlab-ci.yml
stages:
- build
- test
- deploy
build:
stage: build
script:
- docker build -t myapp:$CI_COMMIT_SHA .
test:
stage: test
script:
- docker run myapp:$CI_COMMIT_SHA npm test
deploy:
stage: deploy
only:
- main
script:
- docker tag myapp:$CI_COMMIT_SHA username/myapp:latest
- docker push username/myapp:latest
Use Case: Application CI/CD
# .github/workflows/myapp.yml
name: MyApp CI/CD
on:
push:
branches: [main, develop]
jobs:
test:
runs-on: ubuntu-latest
services:
postgres:
image: postgres:15
env:
POSTGRES_DB: test_db
POSTGRES_USER: test
POSTGRES_PASSWORD: test
options: >-
--health-cmd pg_isready
--health-interval 10s
--health-timeout 5s
--health-retries 5
ports:
- 5432:5432
steps:
- uses: actions/checkout@v3
- name: Build and test
run: |
docker build -t myapp-api:test .
docker run --network host myapp-api:test npm test
deploy:
needs: test
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Deploy to production
run: |
docker build -t myapp-api:latest .
docker push username/myapp-api:latest
# Deploy to the server
Everyday Use Case
Case: A developer pushes code, and it is deployed automatically.
# Push to GitHub
git push origin main
# GitHub Actions will:
# 1. Build the image
# 2. Run the tests
# 3. Push to Docker Hub
# 4. Deploy to the server
Best Practices
- Use multi-stage builds: For smaller images
- Cache dependencies: For faster builds
- Run tests in a container: For consistency
- Use secrets: For credentials
- Rollback strategy: Prepare a way to roll back if a deployment fails
Conclusion
CI/CD with Docker automates the deployment process. For applications, use GitHub Actions or GitLab CI for automation.