Debug Golang dockerized project tests

5 days ago 7
ARTICLE AD BOX

I have a Golang project, a single page application in React, where golang works as static files server and API. The application can be run using docker compose up and npm run in the web folder.

Here the compose.yaml:

services: server: container_name: hello-world-server build: context: . target: development volumes: - .:/app - gomodcache:/go/pkg/mod ports: - 40531:8080 - 40532:12345 env_file: .env depends_on: - db db: container_name: hello-world-db image: postgres:16-alpine environment: POSTGRES_PASSWORD: postgres PGUSER: postgres ports: - 40533:5432 volumes: - ./initdb:/docker-entrypoint-initdb.d - dbdata:/var/lib/postgresql/data healthcheck: test: ["CMD", "pg_isready"] interval: 1s timeout: 10s retries: 10 adminer: container_name: hello-world-adminer image: adminer:latest restart: always ports: - 40534:8080 volumes: gomodcache: null dbdata: null

The Dockerfile:

FROM golang:1.25-alpine AS base WORKDIR /app FROM base AS development RUN apk add build-base # Create external debugger RUN go install github.com/go-delve/delve/cmd/dlv@latest # Restart server on code change RUN go install github.com/cespare/reflex@latest COPY reflex.conf / ENTRYPOINT ["reflex", "-c", "/reflex.conf"] FROM node:25-alpine AS node-builder WORKDIR /app # Copy application dependency manifests to the container image. # A wildcard is used to ensure copying both package.json AND package-lock.json (when available). # Copying this first prevents re-running npm install on every code change. COPY web/package*.json ./ RUN npm ci COPY web . RUN npm run build FROM base AS go-builder # Retrieve application dependencies. # This allows the container build to reuse cached dependencies. # Expecting to copy go.mod and if present go.sum. COPY go.* ./ RUN go mod download # Copy local code to the container image. COPY . . COPY --from=node-builder /app/dist /app/web/dist # Build the binary. RUN go build -buildvcs=false -v -o server FROM alpine:latest # Copy the binary to the production image from the builder stage. COPY --from=go-builder /app/server /app/server # Run the web service on container startup. CMD ["/app/server"]

Using reflex.config and launch.json debugging http calls do work as expected.

I need to add and debug some tests. In the yaml file I added a service:

test: container_name: hello-world-test build: context: . target: test volumes: - .:/app - gomodcache:/go/pkg/mod env_file: .env depends_on: - db

and in the Dockerfile a stage:

FROM base AS test # Copy Go modules COPY go.* ./ RUN go mod download # Copy full source code COPY . . # Default command to run tests CMD ["go", "test", "./...", "-v"]

I can run the test using the command docker-compose run test, but I am not able to run them in debug.

How can I debug my tests? How do I attach the debugger? I am using just VSCode.

Read Entire Article