githubEdit

NATS and Docker

NATS Server Containerization

The NATS server is provided as a Docker image on Docker Hubarrow-up-right that you can run using the Docker daemon. The NATS server Docker image is extremely lightweight, coming in under 10 MB in size.

Synadiaarrow-up-right actively maintains and supports the NATS server Docker image.

Nightly

The nightly build container can be found herearrow-up-right

Usage

To use the Docker container image, install Docker and pull the public image:

docker pull nats

Run the NATS server image:

docker run nats

By default the NATS server exposes multiple ports:

  • 4222 is for clients.

  • 8222 is an HTTP management port for information reporting.

  • 6222 is a routing port for clustering.

The default ports may be customized by providing either a -p or -P option on the docker run command line.

The following steps illustrate how to run a server with the ports exposed on a docker network.

First, create the docker network 'nats:'

Then start the server:

Creating a NATS Cluster

First, run a server with the ports exposed on the 'nats' docker network:

Next, start additional servers pointing them to the seed server to cause them to form a cluster:

NOTE Since the Docker image protects routes using credentials we need to provide them above. Extracted from Docker image configurationarrow-up-right

To verify the routes are connected, you can make a request to the monitoring endpoint on /routez and confirm that there are now 2 routes:

Creating a NATS Cluster with Docker Compose

It is also straightforward to create a cluster using Docker Compose. Below is a simple example that uses a network named 'nats' to create a full mesh cluster.

Now we use Docker Compose to create the cluster that will be using the 'nats' network:

Testing the Clusters

Now, the following should work: make a subscription on one of the nodes and publish it from another node. You should be able to receive the message without problems.

Inside the container:

Stopping the seed node, which received the subscription, should trigger an automatic failover to the other nodes:

Output extract:

Publishing again will continue to work after the reconnection:

Tutorial

See the NATS Docker tutorial for more instructions on using the NATS server Docker image.

Last updated

Was this helpful?