title | author | date |
---|---|---|
Developing on localhost with NATS in Docker |
Alan Sandoval <[email protected]> |
Dec 6, 2023 |
Kubernetes is very complex, so let's get around it for development of applications. In this guide, you will learn to:
- run a NATS server with Docker
- run a NATS-box to act as a NATS client
- pub and sub to/from NATS with the NATS-box
- configure nsc to create NATS JWTs with the 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
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
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.
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
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