Skip to content

TLS certificates

Interacting with services that require TLS certificates is a common issue when working with containers. You can create one or more on-the-fly certificates in order to communicate with your services.

Testcontainers for Go uses a library to generate certificates on-the-fly. This library is called tlscert.

Examples

In the following example we are going to start an HTTP server with a self-signed certificate. It exposes one single handler that will return a simple message when accessed. The example will also create a client that will connect to the server using the generated certificate, demonstrating how to use the generated certificate to communicate with a service.

caCert := tlscert.SelfSignedFromRequest(tlscert.Request{
    Name:      "ca",
    Host:      "localhost,127.0.0.1",
    IsCA:      true,
    ParentDir: certDirs,
})
if caCert == nil {
    log.Print("failed to generate CA certificate")
    return
}
cert := tlscert.SelfSignedFromRequest(tlscert.Request{
    Name:      "client",
    Host:      "localhost,127.0.0.1",
    IsCA:      true,
    Parent:    caCert,
    ParentDir: certDirs,
})
if cert == nil {
    log.Print("failed to generate certificate")
    return
}