Writing tests for Couchbase with Testcontainers on Golang

This a brief example of using Testcontainers with a vanilla Couchabse Community docker image to spin up a container on which database tests can be run against. I was not able to find any good example online which uses the vanilla image, and had to spend more time than I wished to have. To save time for the next person, I write this blog (being aware of the irony in spending even more time).

This setup requires two basic steps:

1. Starting a Couchbase container with the required ports exposed

Apart from the typical container startup code, the Couchbase container additionally requires port forwarding of all required service ports. For example, running a query will require you to expose the at which the listens to. The usage of these ports might not be apparent when using the Go Couchbase SDK to make queries. Some of these service ports are also used internally by the SDK to check whether the cluster is ready, unless explicitly overridden.

The following set of port forwards can be good place to start, and can be extended as needed. Forwarding the container ports to the same host ports will make life easier for us as we would not have to discover the allocated host ports for each service port, and configure it when using the SDK.

2. Initializing the Couchabse Cluster

After the container has started, it requires a few steps of setup before it is ready to use. The steps are:

  1. Initialize the node
  2. Set up the Couchbase Server services
  3. Set memory quotas
  4. Establish the administrator name and password

As already discussed in the given reference, curl commands are used for these steps. Once these commands are successfully run, the cluster will be ready for testing. You can also login to the UI at with the credentials which are hard coded in the below code.

Running a Test

Now that the cluster is ready, we can write a test to verify the cluster connection and readiness. The below test starts the Couchbase container and prepares its single node cluster. Then it tries to verify cluster readiness using the function. It is also made sure that the container is terminated after the test, using on the method. During the test, we assert all errors are nil and that the container and cluster objects are not nil.

This setup can be extended to write a DB test suite with the container creation and cluster setup as the and container termination as the .

Senior Consultant | Trekking & Cycling enthusiast