know-how.dev

How to use Google PubSub locally with emulator

3 years ago 1734

gcloud command-line tool provides awesome feature called emulators - it allows to emulate google cloud's services locally and that's very useful for local development and testing.

How to run Google PubSub locally using gcloud tool:

  1. Install the emulator:
gcloud components install pubsub-emulator
gcloud components update
  1. Start it:
gcloud beta emulators pubsub start --project=PUBSUB_PROJECT_ID

PUBSUB_PROJECT_ID must be replaced with the project ID you want to use. It shouldn't be a real project ID because it doesn't matter for the emulator.

The emulator uses port 8085 by default, so you can access it at localhost: 8085. All main operations are available, such as:

  • Creating topic or subscription
  • Publishing
  • Subscribing

But note that the emulator is not a real Google PubSub service, some features can be missed or work in a different manner.

Read more about emulator features in docs.

You can also use non-official docker image in case if you use docker-compose, k8s or just don't want to install gcloud CLI tool or it's components.

docker run --rm -ti -p 8681:8681 messagebird/gcloud-pubsub-emulator:latest

The image also allows creating topics and subscriptions automatically on startup by passing environment variables:

docker run --rm -ti -p 8681:8681 -e PUBSUB_PROJECT1=PROJECTID,TOPIC1,TOPIC2:SUBSCRIPTION1

Read more about automatic topic and subscription creation here.