简体   繁体   中英

Why ConnectionError using python in docker-compose?

I have this

docker-compose:

version: '3.3'

services:
  bd_mySql:
    image: mysql:5.7     
    restart: always
    ports:
      - "3306:3306"
    environment:
      MYSQL_USER: razvan
      MYSQL_PASSWORD: PepitoElDeLosPalotes
      MYSQL_ROOT_PASSWORD: PepitoElDeLosPalotes
      MYSQL_DATABASE: equipojugadores
  api:
    build: data
    restart: always
    ports:
      - "8084:8084"
  python:
    build: python
    restart: on-failure
    depends_on: 
      - api      

dockerfile (python)

FROM python:latest

ADD scraper.py /

RUN pip install BeautifulSoup4
RUN pip install html5lib
RUN pip install requests
RUN pip install lxml

CMD [ "python", "scraper.py" ]

我的一些python代码 And i have this error:

requests.exceptions.ConnectionError: HTTPConnectionPool(host='localhost', port=8084):

why?

Your scraper.py code is trying to connect to localhost:8004 , however you have placed the service that advertises port 8004 on a separate container. This is similar to if you had placed it on a separate machine, and so localhost won't reach it. Instead, you have to use api:8004 , which will resolve to the IP of the api container, which is where you put this service.

Your py code is trying to connect with localhost for that you need provide links in python part.
After that you can call the request http://api:8084/apiname .
This worked for me:

api:
    build: data
    restart: always
    ports:
      - "8084:8084"
python:
    build: python
    restart: on-failure
    depends_on: 
      - api
    links:
      - api

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