
Docker from Scratch, Part 4: Server Deployment and Rollback in a Minute
🌐 Machine-translated from Russian. Show original
In this part:
Deployment scheme#
- CI assembled the image of
ghcr.io/org/app:<sha>(part 3. - CI connects to the server via SSH and says: "run version ."
- The server downloads the image, applies migrations, and restarts the container.
- Healthcheck confirms that the new version works. If not — rollback to the previous tag.
Server preparation#
- An individual user
deployin thedockergroup, login only by key. - On the server —
compose.yamland.envwith secrets (secrets are not stored in the repository). - In compose, the image version is taken from the variable:
services:
api:
image: ghcr.io/org/app:${APP_VERSION}
env_file: .env
restart: unless-stopped
Server deployment script#
/opt/app/deploy.sh:
#!/usr/bin/env bash
set -euo pipefail
cd /opt/app
NEW="$1"
PREV=$(cat .version 2>/dev/null || echo "")
export APP_VERSION="$NEW"
docker compose pull api
docker compose run --rm api npm run migrate # миграции до переключения
docker compose up -d api
for i in $(seq 1 30); do
if curl -fsS http://127.0.0.1:3000/health >/dev/null; then
echo "$NEW" > .version; echo "OK: $NEW"; exit 0
fi
sleep 2
done
echo "Новая версия не поднялась, откат на $PREV"
[ -n "$PREV" ] && APP_VERSION="$PREV" docker compose up -d api
exit 1
Job deployment in CI#
Add to the pipeline from part 3 (GitHub Actions):
deploy:
needs: image
runs-on: ubuntu-latest
environment: production
steps:
- name: Deploy over SSH
run: |
install -m 600 /dev/null key
echo "${{ secrets.DEPLOY_KEY }}" > key
ssh -i key -o StrictHostKeyChecking=accept-new deploy@${{ secrets.DEPLOY_HOST }} \
"/opt/app/deploy.sh ${{ github.sha }}"
environment: production allows enabling manual confirmation of deployment to prod in the repository settings.
Rollback#
Rollback is simply the launch of the previous tag:
ssh deploy@server "/opt/app/deploy.sh <предыдущий-sha>"
Therefore, never deploy latest: with SHA tags, each version is unambiguous and recovers within a minute.
Database migrations without pain#
- Migrations must be backward compatible: first add a column, roll out the code that uses it, and only with the next release remove the old one.
- Then code rollback does not break the base, and the base almost never needs to be rolled back.
- Before risky migrations — a fresh backup of the base.
Zero-downtime#
The simple scheme above gives several seconds of unavailability upon restart. If critical:
- hold two instances of the app by nginx/Caddy and update them one by one;
- or use an orchestrator (Docker Swarm, Kubernetes) — but for a single server, this is often redundant.
🎉 Series completed: code checks for each commit, verified image goes to the server, rollback — one command. Return to series content.
Comments · 0
No comments yet.Sign in to comment, rate and see all comments.