Introduction
Container security scanning is the process of automatically checking Docker images for known vulnerabilities, insecure configurations, and exposed secrets before they reach production. In a GitLab CI workflow for a Node.js application, you can embed this step so that every commit that produces a new image is vetted without manual effort.
By the end of this guide you will have a reproducible GitLab CI pipeline that builds a Node.js Docker image, scans it with Trivy, rejects builds that exceed your vulnerability threshold, stores secrets safely with GitLab CI/CD variables, and optionally renews SSL certificates with Certbot during deployment.
What You’ll Learn
- How to configure GitLab CI to build and push a Node.js Docker image.
- How to run a container‑security‑scanner (Trivy) inside the pipeline.
- How to enforce vulnerability thresholds and fail fast.
- How to keep secrets out of Dockerfiles using GitLab’s secret management.
- How to automate SSL certificate renewal as part of the same pipeline.
Prerequisites
- A GitLab project with GitLab CI/CD enabled.
- GitLab Container Registry access (default for all projects on GitLab.com).
- Node.js source code with a
package.jsonthat can be built withnpm ciorpnpm install. - Docker Engine (or Docker‑compatible runtime) available on the GitLab shared runners or on a self‑hosted runner.
- Basic familiarity with Trivy or another scanner (Anchore Engine, Clair, etc.).
Pipeline Overview
The pipeline consists of three main jobs:
- build – builds the Docker image and pushes it to the GitLab Container Registry.
- scan – pulls the image, runs Trivy, and fails if vulnerabilities exceed the allowed threshold.
- deploy – deploys the image (e.g., to Kubernetes) and runs Certbot to keep TLS certificates up to date.
Each job runs in its own Docker executor, and the scan job uses the same image that was built, guaranteeing you test exactly what will be deployed.
Write a Secure Dockerfile for Node.js
Start with an official, minimal base image and avoid installing unnecessary packages.
FROM node:20-alpine AS builder
WORKDIR /app
# Install only production dependencies
COPY package*.json ./
RUN npm ci --only=production
COPY . .
RUN npm run build # if you have a build step
# Runtime stage – use a non‑root user
FROM node:20-alpine
WORKDIR /app
COPY --from=builder /app /app
# Create a non‑root user
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
USER appuser
EXPOSE 3000
CMD ["node", "dist/index.js"]
Key hardening points:
- Use
alpineto keep the attack surface small. - Run as a non‑root user.
- Do not copy
.envor other secret files into the image.
Set Up GitLab CI Variables (Secrets Management)
Store any runtime secrets (e.g., database passwords, API keys) as protected CI/CD variables. GitLab masks them in job logs and makes them available only to protected branches.
| Variable name | Scope | Example value |
|---|---|---|
| DB_PASSWORD | Protected, masked | myS3cureP@ss |
| SSL_EMAIL | Protected | admin@example.com |
| TRIVY_SEVERITY | Protected | HIGH,CRITICAL |
Reference the variables in .gitlab-ci.yml with $VARIABLE_NAME. Because the Dockerfile never sees these values, they cannot be baked into the image.
Build Stage
image: docker:latest
services:
- docker:dind
variables:
# Use the GitLab Container Registry path
IMAGE_TAG: $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA
stages:
- build
- scan
- deploy
build:
stage: build
script:
- docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" $CI_REGISTRY
- docker build -t $IMAGE_TAG .
- docker push $IMAGE_TAG
only:
- branches
Scan Stage with Trivy
Trivy is a free, open‑source scanner that checks OS packages, language libraries, and misconfigurations. Install it in the job container and run against the image you just pushed.
scan:
stage: scan
image:
name: aquasec/trivy:latest
entrypoint: [""]
script:
# Pull the image to ensure the scanner sees the exact layers
- docker pull $IMAGE_TAG
# Scan for vulnerabilities; output as JSON for CI parsing
- trivy image --severity $TRIVY_SEVERITY --exit-code 1 --format json -o trivy-report.json $IMAGE_TAG
artifacts:
reports:
dependency_scanning: trivy-report.json
dependencies:
- build
only:
- branches
Explanation of flags:
--severity– limits the scan to the severities you care about (e.g., HIGH,CRITICAL).--exit-code 1– makes the job fail if any matching vulnerability is found.--format json– enables GitLab’s built‑in Dependency Scanning UI.
Deploy Stage with SSL Automation
Assuming you deploy to a Kubernetes cluster, you can use cert-manager or run Certbot on a bastion host. The example below shows a simple SSH‑based deployment that also renews a Let's Encrypt certificate via Certbot.
deploy:
stage: deploy
image: alpine:latest
before_script:
- apk add --no-cache openssh-client certbot
# Add the CI SSH key (protected variable) to the ssh-agent
- eval $(ssh-agent -s)
- echo "$DEPLOY_SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add -
- mkdir -p ~/.ssh
- echo "$DEPLOY_KNOWN_HOSTS" > ~/.ssh/known_hosts
script:
# Pull the image on the target host
- ssh $DEPLOY_USER@$DEPLOY_HOST "docker pull $IMAGE_TAG && docker tag $IMAGE_TAG myapp:latest && docker compose up -d"
# Renew SSL certificate if needed (runs in the same SSH session)
- ssh $DEPLOY_USER@$DEPLOY_HOST "certbot renew --quiet --deploy-hook 'docker restart myapp'"
only:
- main
Key points:
- Store
DEPLOY_SSH_PRIVATE_KEYandDEPLOY_KNOWN_HOSTSas protected CI variables. - Certbot’s
--deploy-hookrestarts the container after a certificate renewal, ensuring the new cert is used immediately.
Pro Tips
Run Trivy with the
--skip-db-updateflag on runners that already have a cached database to reduce scan time. Refresh the DB on a nightly schedule with a separate pipeline.
Combine Trivy with Grype if you need SBOM comparison against your internal allow‑list.
Enable GitLab’s Dependency Scanning UI to view vulnerability details directly in merge requests.
Frequently Asked Questions
Can I use a different scanner, such as Anchore Engine?
Yes. Replace the scan job image with the Anchore Engine CLI image, set the appropriate environment variables, and adjust the exit‑code handling. The overall pipeline structure stays the same.
How do I set a custom vulnerability threshold per severity?
Define CI variables like MAX_HIGH=5 and use a small script to parse Trivy’s JSON output, exiting with a non‑zero code if the count exceeds the limit.
Is it safe to store Docker Hub credentials in GitLab variables?
Store them as protected and masked** variables. GitLab masks them in job logs and only makes them available to protected branches, reducing exposure.
What if my pipeline runs on shared runners without Docker‑in‑Docker support?
Enable the docker executor in your project settings, or use a self‑hosted runner with the Docker socket mounted (-v /var/run/docker.sock:/var/run/docker.sock).
How can I scan for secrets that may have been accidentally added to the image?
Trivy includes a secret scanner mode (trivy image --secret). For deeper analysis, integrate git‑secrets in the build stage before the Docker build.
Do I need to scan the same image twice (once locally, once in CI)?
Scanning in CI guarantees that the exact image pushed to the registry is examined. Local scans are useful for early feedback but are not a substitute for CI enforcement.
Can the pipeline also enforce SSL certificate expiration checks?
Yes. Add a step that runs openssl x509 -checkend 2592000 -noout -in /path/to/cert.pem (30‑day threshold) and fail the job if the cert expires soon.
Conclusion
Implement the three‑stage pipeline described above to make container security scanning an automatic gatekeeper for every Node.js Docker image. After the pipeline is in place, you can extend it with:
- Nightly DB updates for Trivy.
- Automated SBOM generation with SPDX.
- Policy‑as‑code using OPA to reject images that violate custom rules.
Start by committing the .gitlab-ci.yml file, set the required CI variables, and watch the first pipeline enforce both vulnerability thresholds and secret‑free images.

