201 β€” Building Docker Images in CI/CD

Intermediate

Automate Docker image builds in GitHub Actions. Learn tagging strategies, build optimization, and how to build images for every commit automatically.

Learning Objectives

1
Build Docker images automatically in CI pipelines
2
Implement semantic versioning for image tags
3
Use Docker Buildx for multi-platform builds
4
Optimize image builds with layer caching
5
Tag images based on Git commits and branches
Step 1

Create a containerized application

Set up a Node.js app with Dockerfile for CI/CD practice.

Commands to Run

mkdir docker-ci-app && cd docker-ci-app
npm init -y
npm install express
cat > app.js << 'EOF'
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;

app.get('/', (req, res) => {
  res.json({ 
    message: 'Hello from Docker CI!',
    version: process.env.APP_VERSION || 'dev',
    commit: process.env.GIT_COMMIT || 'unknown'
  });
});

app.get('/health', (req, res) => {
  res.json({ status: 'healthy', timestamp: new Date().toISOString() });
});

app.listen(PORT, '0.0.0.0', () => {
  console.log(`Server running on port ${PORT}`);
});
EOF
cat > Dockerfile << 'EOF'
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY app.js .
EXPOSE 3000
CMD ["node", "app.js"]
EOF
docker build -t docker-ci-app:local .
docker run -d -p 3000:3000 --name test-app docker-ci-app:local
curl http://localhost:3000
docker stop test-app && docker rm test-app

What This Does

We create an Express app that displays version and commit info from environment variables. The Dockerfile uses best practices: Alpine base, npm ci, and proper layer ordering.

Expected Outcome

App builds and runs successfully. curl returns JSON with message, version, and commit. Container stops cleanly.

Pro Tips

  • 1
    Alpine images are smaller and faster to build/pull
  • 2
    npm ci --only=production excludes dev dependencies
  • 3
    Environment variables allow runtime configuration
  • 4
    Test Docker builds locally before CI automation
Was this step helpful?

All Steps (0 / 11 completed)