Skip to content

TLS Strategy

TLS Strategy waits for one or more files to exist in the container and uses them and other details to construct a tls.Config which can be used to create secure connections.

It supports:

  • x509 PEM Certificate loaded from a certificate / key file pair.
  • Root Certificate Authorities aka RootCAs loaded from PEM encoded files.
  • Server name.
  • Startup timeout to be used in seconds, default is 60 seconds.
  • Poll interval to be used in milliseconds, default is 100 milliseconds.

Waiting for certificate pair

The following snippets show how to configure a request to wait for certificate pair to exist once started and then read the tls.Config, alongside how to copy a test certificate pair into a container image using a Dockerfile.

It should be noted that copying certificate pairs into an images is only an example which might be useful for testing with testcontainers-go and should not be done with production images as that could expose your certificates if your images become public.

// The file names passed to ForTLSCert are the paths where the files will
// be copied to in the container as detailed by the Dockerfile.
forCert := wait.ForTLSCert("/app/tls.pem", "/app/tls-key.pem").
    WithServerName("testcontainer.go.test")
req := testcontainers.ContainerRequest{
    FromDockerfile: testcontainers.FromDockerfile{
        Context: "testdata/http",
    },
    WaitingFor: forCert,
}
config := forCert.TLSConfig()
FROM golang:1.18-alpine@sha256:77f25981bd57e60a510165f3be89c901aec90453fd0f1c5a45691f6cb1528807 as builder
WORKDIR /app
COPY . .
RUN mkdir -p dist
RUN go build -o ./dist/server main.go

FROM alpine
WORKDIR /app
COPY --from=builder /app/tls.pem /app/tls-key.pem ./
COPY --from=builder /app/dist/server .
EXPOSE 6443
CMD ["/app/server"]