2.5 KiB
2.5 KiB
NATS Messaging System
A simple NATS client/server setup for testing message publishing and subscribing using Docker Compose.
Architecture
- NATS Server: Message broker running on port 4222
- Server (index.ts): Subscribes to messages and displays them
- Client (client.ts): Interactive CLI for publishing messages
Prerequisites
- Docker and Docker Compose
- (Optional) Bun runtime for local development
Running with Docker Compose (Recommended)
1. Start the NATS server and message subscriber
docker compose up nats server
This starts:
- NATS message broker in the background
- Server that subscribes to messages and displays them
2. Run the interactive client
docker compose run --rm client
This opens an interactive prompt where you can:
- Type messages and press Enter to send them
- Type
quitorexitto stop the client - Use Ctrl+C to force exit
3. View server logs (optional)
To see incoming messages in real-time:
docker compose logs -f server
4. Stop everything
docker compose down
Example Usage
-
Terminal 1: Start the infrastructure
docker compose up nats server -d -
Terminal 2: Run the client
docker compose run --rm clientYou'll see:
Connected to NATS at nats://nats:4222 Enter a message (or 'quit' to exit): Hello World! Enter a message (or 'quit' to exit): This is a test Enter a message (or 'quit' to exit): quit Goodbye! -
Terminal 1: Check server logs to see received messages
docker compose logs server
Local Development (without Docker)
If you prefer to run locally:
Install dependencies
bun install
Start NATS server
docker run -p 4222:4222 nats:latest
Run the server (in one terminal)
bun run index.ts
Run the client (in another terminal)
bun run client.ts
Environment Variables
NATS_SERVER: NATS server URL (default:nats://localhost:4222)
Troubleshooting
- Client not accepting input: Make sure you're using
docker compose run --rm clientinstead ofdocker compose up client - Connection refused: Ensure NATS server is running first
- Messages not appearing: Check that the server container is running with
docker compose ps
This project was created using bun init in bun v1.2.18. Bun is a fast all-in-one JavaScript runtime.