How to connect to rabbitmq container from the application server container

那年仲夏 提交于 2019-12-11 17:19:20

问题


I am new to docker and I am trying to dockerize this application I have written in Golang. It is a simple web server that interacts with rabbitmq and mongodb

It takes the creadentials form a toml file and loads it into a config struct before starting the application server on port 3000. These are the credentials

mongo_server = "localhost"
database = "collect_db"
rabbitmq_server = "amqp://guest:guest@localhost:5672/"

If it can't connect to these urls it fails with an error. Following is my docker-compose.yml

version: '3'
services:
  rabbitmq:
    image: rabbitmq 
    ports:
      - 5672:5672
  mongodb:
    image: mongo
    ports:
      - 27017:27017
  web:
    build: .
    image: palash2504/collect
    container_name: collect_service
    ports:
      - 3000:3000
    depends_on:
      - rabbitmq
      - mongodb
    links: [rabbitmq, mongodb]

But it fails to connect with rabbitmq on the url used for local development i.e. amqp://guest:guest@localhost:5672/

I realise that the rabbitmq container might be running on some different address other than the one provided in the config file.

I would like to know the correct way for setting any env credentials to be able to connect my app to rabbitmq.

Also what approach would be best to change my application code for initializing connections to external services? I was thinking about ditching the config.toml file and using os.Getenv and os.Setenv to get the urls for connections.


回答1:


Localhost addresses are resolved, well, locally. They thus will not work inside containers, since they will look for a local address (i.e. inside the container).

Services can access each other by using service names as an address. So in the web container you can target mongodb for example.

You might give this a shot:

mongo_server = mongodb
database = "collect_db"
rabbitmq_server = "amqp://guest:guest@rabbitmq/"

It is advisable to set service target environment variables in the compose file itself:

#docker-compose.yml

#...other stuff...

web:
    #...other stuff...
    environment:
      RABBITMQ_SERVER: rabbitmq
      MONGO_SERVER: mongodb
    depends_on:
      - rabbitmq
      - mongodb

This gives you a single place to make adjustments to the configuration.

As a side note, to me it seems that links: [rabbitmq, mongodb] can be removed. And I would advise not to alter the container name (remove container_name: collect_service unless it is necessary)



来源:https://stackoverflow.com/questions/55077073/how-to-connect-to-rabbitmq-container-from-the-application-server-container

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!