Deploying a Docker Service with GitHub Actions: GHCR, Digests and Secrets Done Right

Deploying a containerized service by hand (build an image, push it, SSH into a server, pull, restart) is slow and easy to get subtly wrong. A GitHub Actions workflow can do the same steps on every merge to main, the same way every time.
This guide builds that pipeline for a service deployed to a single VM with Docker: build and push to GitHub Container Registry (GHCR), then deploy the exact image that was built, with a manual approval gate. It pays particular attention to secrets: which credentials the pipeline needs, how to scope them, how the application gets its own runtime secrets without them passing through CI, and how to avoid long-lived cloud keys altogether.
What Goes Wrong Without a Pipeline
With more than one or two services, manual deployments tend to fail in the same ways:
Environment Drift: What works on dev doesn't work on staging or production due to inconsistent configurations or dependencies.
Manual Bottlenecks: Every deployment requires a human to log in, run commands, and verify, leading to delays and potential errors.
Secret Sprawl: API keys, database credentials, and other sensitive data end up in various places – config files, environment variables, or even source control – without proper management.
Not knowing what's running: if the server runs
:latest, nobody can say which commit is in production, and rolling back means guessing.
Setting the Stage: Our Sample Microservice
For this tutorial, let's imagine a simple Node.js microservice that exposes a /health endpoint. The core idea remains the same whether it's Node.js, Python, Go, or Java. What's crucial is its containerization using a Dockerfile.
Step-by-Step Guide: Automating Your Deployment Pipeline
Step 1: Containerizing Your Application
First, we need a Dockerfile to package our microservice. This ensures that our application and all its dependencies are self-contained and run consistently across any environment supporting Docker.
FROM node:22-alpine
WORKDIR /app
# Install production dependencies exactly as locked
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
# Run as the unprivileged user the image provides
USER node
EXPOSE 3000
CMD ["node", "server.js"]Add a .dockerignore containing at least node_modules, .git and .env. Otherwise COPY . . can bake a local .env file, with real credentials, into the image, where anyone who can pull the image can read it.
Step 2: Defining Your GitHub Actions Workflow
GitHub Actions workflows are defined in YAML files located in the .github/workflows directory of your repository. Each workflow specifies a series of jobs, and each job consists of steps. Our workflow will trigger on pushes to the main branch.
Step 3: Building and Pushing Docker Images
The workflow pushes to GHCR using the automatically provided GITHUB_TOKEN, so no registry password needs to be stored. The token is valid only while the job runs and has only the permissions the job requests.
Create a file named deploy.yml inside .github/workflows/.
name: CI/CD Pipeline for Microservice
on:
push:
branches:
- main
env:
REGISTRY: ghcr.io
# Image names must be lowercase; repository names often aren't (e.g. "MyOrg/My-Service").
IMAGE: ghcr.io/my-org/my-node-microservice
jobs:
build-and-push:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write # Required to push to GHCR
outputs:
image: ${{ env.IMAGE }}@${{ steps.build.outputs.digest }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Log in to GitHub Container Registry
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract metadata (tags) for Docker
id: meta
uses: docker/metadata-action@v5
with:
images: ${{ env.IMAGE }}
tags: |
type=sha,format=short,prefix=sha-
type=ref,event=branch
- name: Build and push Docker image
id: build
uses: docker/build-push-action@v6
with:
context: .
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=maxThe job tags each image with the commit (sha-1a2b3c4) and the branch, and caches build layers in the GitHub Actions cache (type=gha) so unchanged layers aren't rebuilt. It also exports the image's digest (sha256:...) as a job output. A digest identifies the exact image content and, unlike a tag, can never point to anything else, which makes it the right thing to deploy.
Step 4: Secure Secret Management
This pipeline handles three kinds of credentials, and each should be handled differently:
- Registry credentials for pushing: the job's
GITHUB_TOKEN, as above. Nothing to store. - Access to the deployment target: an SSH key here. Store it as a secret on a GitHub Environment named
production, not as a repository secret. Environment secrets are only available to jobs that reference the environment, so you can require a reviewer's approval before any job can use them. - The application's runtime secrets (database password, third-party API keys): these shouldn't pass through CI at all. Keep them on the server, or in a secret manager the server reads from, and let the container load them at start-up. The pipeline then never handles them, and they don't appear in workflow logs or in the image.
Create the environment under Settings → Environments → New environment, add required reviewers, and add these secrets to it:
SSH_PRIVATE_KEY: a key created only for deployments, whose server-side user can run Docker and nothing else.SSH_HOST,SSH_USER: the server's address and that user.SSH_KNOWN_HOSTS: the server's host key fingerprint (fromssh-keyscan -t ed25519 your-server), so the workflow refuses to connect to an impostor.GHCR_PULL_TOKEN: a fine-grained or classic personal access token limited toread:packages, used by the server to pull private images. Don't reuse the job'sGITHUB_TOKENon the server: it expires when the job ends, and the server needs to pull again later, for example when Docker restarts the container on a new host.
💡 Tip: If you deploy to AWS, Google Cloud or Azure, use GitHub's OpenID Connect (OIDC) integration instead of storing cloud access keys. The workflow exchanges a short-lived GitHub-signed token for temporary cloud credentials scoped to one role, so there's no long-lived key to leak or rotate.
Step 5: Deploying to Production (Example: SSH to a VM)
Add a second job that waits for the build, pauses for approval, and deploys the exact digest that was built. On the server, the application's runtime configuration lives in /etc/my-service/app.env (readable only by the deploy user), created once by hand or by your configuration management.
deploy:
runs-on: ubuntu-latest
needs: build-and-push
environment: production # waits for required reviewers; unlocks environment secrets
steps:
- name: Deploy over SSH
env:
IMAGE: ${{ needs.build-and-push.outputs.image }}
SSH_KEY: ${{ secrets.SSH_PRIVATE_KEY }}
KNOWN_HOSTS: ${{ secrets.SSH_KNOWN_HOSTS }}
TARGET: ${{ secrets.SSH_USER }}@${{ secrets.SSH_HOST }}
run: |
install -m 700 -d ~/.ssh
echo "$SSH_KEY" > ~/.ssh/deploy_key && chmod 600 ~/.ssh/deploy_key
echo "$KNOWN_HOSTS" > ~/.ssh/known_hosts
ssh -i ~/.ssh/deploy_key "$TARGET" IMAGE="$IMAGE" 'bash -s' <<'EOF'
set -euo pipefail
docker pull "$IMAGE"
docker rm -f my-service 2>/dev/null || true
docker run -d --name my-service --restart unless-stopped \
--env-file /etc/my-service/app.env \
-p 127.0.0.1:3000:3000 \
"$IMAGE"
# Fail the deployment if the new container doesn't become healthy
for i in $(seq 1 15); do
curl -fsS http://127.0.0.1:3000/health && exit 0
sleep 2
done
docker logs --tail 50 my-service
exit 1
EOFThe server logs in to GHCR once, during setup, with the read-only token (echo "$TOKEN" | docker login ghcr.io -u <user> --password-stdin), so the workflow never sends a registry credential to it.
Notes on this job:
- It deploys a digest (
image@sha256:...), so production runs exactly the image that was built and tested, even if someone pushes another:mainin the meantime. To roll back, rerun the deploy job of an earlier workflow run. It deploys that run's digest. - The health check fails the job if the new container doesn't respond, so a broken release shows up as a red deployment instead of a silent outage.
- There's a short gap between removing the old container and the new one starting. For zero-downtime deployments on a single host, run the new container on a second port and switch a reverse proxy over once it's healthy. At larger scale, use an orchestrator.
Common Mistakes and How to Avoid Them
- Uppercase characters in image names: registries require lowercase repository names, and
${{ github.repository }}is often mixed case, which fails the push with "repository name must be lowercase". - Printing secrets in scripts: GitHub masks known secret values in logs, but not values derived from them (base64-encoded, split, or reformatted). Never
echosecrets or run scripts withset -xwhile secrets are in the environment. - Overlooking Environment Protection Rules: For production deployments, always configure GitHub Environments with protection rules (e.g., manual approval, required reviewers) to prevent accidental or unauthorized deployments.
- Deploying mutable tags:
:latestand:mainchange with every push. Deploy by digest, and keep commit-SHA tags so people can see which commit an image came from. - Running third-party actions with secrets: every action in a job that has secrets can read them. Prefer plain
run:steps for sensitive work, as in the deploy job above, and pin any third-party actions you do use to a commit SHA.
Summary
- Push with the job's
GITHUB_TOKENand grant only the permissions each job needs. - Deploy by digest, never by a mutable tag, so you always know what's running and can roll back.
- Put deployment secrets on a protected environment with required reviewers and a pinned SSH host key.
- Keep application runtime secrets out of CI and out of images: load them on the server with
--env-fileor from a secret manager, and use.dockerignore. - Prefer OIDC over stored cloud keys when deploying to a cloud provider.
