Skip to content

Instantly share code, notes, and snippets.

@SuperCoolAlan
Last active June 7, 2024 18:08
Show Gist options
  • Save SuperCoolAlan/21a577f177f17c8d2a21ce13311a23bb to your computer and use it in GitHub Desktop.
Save SuperCoolAlan/21a577f177f17c8d2a21ce13311a23bb to your computer and use it in GitHub Desktop.
Developing on localhost with NATS in Docker
title author date
Developing on localhost with NATS in Docker
Alan Sandoval <[email protected]>
Dec 6, 2023

Developing with NATS without Kubernetes

Kubernetes is very complex, so let's get around it for development of applications. In this guide, you will learn to:

  1. run a NATS server with Docker
  2. run a NATS-box to act as a NATS client
  3. pub and sub to/from NATS with the NATS-box
  4. configure nsc to create NATS JWTs with the NATS-box

Start NATS-box

NATS-box can be used to publish or subscribe to the NATS server. Additionally, it can be used to create nsc configurations. nsc is used to create and manage NATS user permissions

To run this, use the following command which connects the localhost network to the NATS-box you are running:

docker run -it --rm --network host natsio/nats-box

Configure NATS-box

In order to access the NATS server you ran earlier, export the server's address to an environment variable as defined below:

export NATS_URL=localhost:4222

After configuring the server URL as shown above, you should be able to pub/sub from the NATS-box like shown in the below commands:

nats sub "subtopic"
nats pub "pubtopic" "testmsg"

Sometimes, I run multiple NATS-box to pub and sub at the same time

Configure nsc

In order to use JWTs for NATS, you must first configure users with the nsc cli tool. See an example guide on setting up nsc in these docs.

Explicitly set the nsc directories so that we can find their contents:

export NSC_HOME=~/.nsc
export NKEYS_PATH=~/.nkeys
nsc env -s ~/.nsc/nats

These files will contain the generated JWTs you need to authenticate with a server.

Example nsc

nsc add operator MyOperator
nsc edit operator --service-url nats://localhost:4222
nsc add account MyAccount
nsc add user MyUser
nsc add account -n SYS
nsc edit operator --system-account SYS
nsc generate config --nats-resolver > resolver.conf

Start NATS server

You must provide nsc configs via a volume mount. Take the results of nsc's output in file resolver.conf from above and paste it to a file in your current directory named natsresolver.conf.

To run a NATS server with Docker, simply run the following command:

docker run -p 4222:4222 -v ./natsresolver.conf:/etc/config/resolver.conf nats -c /etc/config/resolver.conf

This command runs the NATS server in a Docker container and makes its service port of 4222 available to your localhost's 4222. This way, we can access the NATS server from localhost:4222

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment