Create a docker-compose.yml file and place the NATS configuration files in the same folder. Then run:
docker compose up -dTo test the NATS server, run:
docker run --network devsetup --rm -it natsio/nats-box
After this command, your terminal will be inside the container. Run the following command to connect to the NATS server:
nats sub -s nats://nats-1:4222 hello &A successful subscription will return something like:
16:27:54 Subscribing on hello Now publish a message to servers 2 and 3:
nats pub -s "nats://nats-2:4222" hello first
# message that should published
16:29:04 Published 5 bytes to "hello"
# message of the subscription of line 16 received the message
[#1] Received on "hello"
first
# Test server 3
nats pub -s "nats://nats-3:4222" hello second
# message that should published
16:30:01 Published 6 bytes to "hello"
# message of the subscription of line 16 received the message
[#3] Received on "hello"
secondTo simulate a node failure, in another terminal run:
docker compose down nats-1In the NATS box, you will see a message like:
16:31:52 Disconnected due to: EOF, will attempt reconnect
16:31:52 Reconnected [nats://172.19.0.4:4222]Notice that in line 16 the subscription was originally connected to nats-1. When you stop that server, the NATS client automatically reconnects to another node in the cluster.
Done!