简体   繁体   中英

How to connect to RabbitMQ using environmental variables (docker-compose)?

Friends, I'm practicing here and developing a system which consists of a webservice and a worker and they communicate to each other through RabbitMQ. I am using Docker-Compose as well. Everything was working fine until I tried to use environment variables. The webservice is now failing to connect to the rabbitmq: "dial tcp 127.0.0.1:5672: connect: connection refused: ..."

Maybe you guys can help me to find out what I am missing. Here are the revenant parts of my code.

The Golang code:

func init() {
    var err error
    url := os.Getenv("AMQP_URL")
    conn, err = amqp.Dial(url)
    if err != nil {
        logErr(err, "Failed to connect to RabbitMQ")
    }
...

My compose-file:

version:  '3.3'
services: 
    blur-rabbitmq: 
        image: rabbitmq:3-alpine
        container_name: blur-rabbitmq
        restart: always
        hostname: rabbitmq
        ports: 
            - 5672:5672
            - 15672:15672
        environment:
            RABBITMQ_DEFAULT_USER: ${RABBITMQ_USER}
            RABBITMQ_DEFAULT_PASS: ${RABBITMQ_PASSWORD} 
            RABBITMQ_DEFAULT_VHOST: "/"
    
    blur-service: 
        depends_on:
            - blur-rabbitmq
        build: .
        container_name: blur-service
        restart: always
        volumes:
            - type: bind
              source: /Users/name/Desktop/source-images
              target: /source-images
        ports: 
            - 8080:8080
        environment:
            AMQP_URL: ${AMQP_URL}

And my .env file:

AMQP_URL=amqp://guest:guest@localhost:5672
RABBITMQ_USER=guest
RABBITMQ_PASSWORD=guest

Any ideas how to debug?

I got it. The mistake was in the .env file:

I should use AMQP_URL=amqp://guest:guest@blur-service:5672 instead of AMQP_URL=amqp://guest:guest@localhost:5672 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM