连接到服务器被拒绝(运行Docker失败)

a1o7rhls  于 2023-04-20  发布在  Docker
关注(0)|答案(1)|浏览(156)

我有一个Python脚本,它从API中提取数据,将其保存到DB中。然后,它从同一DB中的视图中获取数据,并将其作为Excel文件通过电子邮件发送。
我能够构建一个docker-compose.yaml文件,它可以正确启动PostgreSQL DB示例和Adminer。
现在,我正在尝试将我的Python脚本设置为另一个服务,我正在使用Dockerfile来实现这一点。
当我启动我的容器时,我得到下面的错误消息(为了简单起见被截断):

sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) connection to server at "0.0.0.0", port 5432 failed: Connection refused
        Is the server running on that host and accepting TCP/IP connections?

这是我的docker-compose.yaml file

version: '3.8'

services:
  db:
    image: postgres:14.3
    container_name: postgres
    restart: always
    environment:
      - POSTGRES_USER=user
      - POSTGRES_PASSWORD=pass
      - POSTGRES_DB=dbname
    ports:
      - 5432:5432
    volumes:
      - ./init.sql:/docker-entrypoint-initdb.d/init.sql
      - db_data:/var/lib/postgresql/data
  adminer:
    image: adminer:4.8.1
    container_name: adminer
    restart: always
    ports:
      - 8077:8080
    depends_on:
      - db
  app:
    build:
      context: .
      dockerfile: Dockerfile
    depends_on:
      - db

volumes:
  db_data:

下面是我的Dockerfile

FROM python:3.10-slim-buster

# set working directory
WORKDIR /app

# copy requirements file to work directory
COPY pyproject.toml pyproject.toml
COPY poetry.lock poetry.lock

# install poetry
RUN pip install --upgrade pip \
    && pip install poetry

# install dependencies
RUN poetry config virtualenvs.create false \
    && poetry install --no-dev --no-interaction --no-ansi

# add source code to the image
COPY src src

COPY . .

CMD [ "python", "src/main.py" ]

我正在使用Github Codespaces进行这个项目,所以我不确定这是否会以某种方式影响。此外,下面是我的项目结构:

> myproject
    > src
        > __init__.py
        > settings.py
        > main.py
        > utils.py
    > docker-compose.yaml
    > Dockerfile
    > init.sql
    > poetry.lock
    > pyproject.toml
    > README.md

请帮助我解决这个问题,也了解我做错了什么。我一直在网上寻找答案超过2天,但到目前为止没有。
我使用的主机和端口与运行PostgreSQL示例的主机和端口相同,但这仍然没有解决问题。
当我简单地执行python src/main.py时,脚本运行良好。

编辑# 1

def db_connection():
    """ Create SQL engine. """
    conn = f'postgresql://{DB_USER}:{DB_PW}@{DB_HOST}:{DB_PORT}/{DB_NAME}'
    engine = create_engine(conn)
    return engine

这是我用来创建SQL引擎的函数。

DB_HOST = "0.0.0.0"
DB_PORT = "5432"

编辑#2我应用了建议的更改,但仍然不起作用。一些日志:

app_1      | Traceback (most recent call last):
app_1      |   File "/app/src/main.py", line 60, in <module>
app_1      |     main()
app_1      |   File "/app/src/main.py", line 54, in main
app_1      |     csv_data = get_filtered_data(engine, '...')
app_1      |   File "/app/src/utils.py", line 45, in get_filtered_data
app_1      |     with engine.connect() as conn:
app_1      |   File "/usr/local/lib/python3.10/site-packages/sqlalchemy/engine/base.py", line 3251, in connect
app_1      |     return self._connection_cls(self)
app_1      |   File "/usr/local/lib/python3.10/site-packages/sqlalchemy/engine/base.py", line 147, in __init__
app_1      |     Connection._handle_dbapi_exception_noconnection(
app_1      |   File "/usr/local/lib/python3.10/site-packages/sqlalchemy/engine/base.py", line 2413, in _handle_dbapi_exception_noconnection
app_1      |     raise sqlalchemy_exception.with_traceback(exc_info[2]) from e
app_1      |   File "/usr/local/lib/python3.10/site-packages/sqlalchemy/engine/base.py", line 145, in __init__
app_1      |     self._dbapi_connection = engine.raw_connection()
app_1      |   File "/usr/local/lib/python3.10/site-packages/sqlalchemy/engine/base.py", line 3275, in raw_connection
app_1      |     return self.pool.connect()
app_1      |   File "/usr/local/lib/python3.10/site-packages/sqlalchemy/pool/base.py", line 455, in connect
app_1      |     return _ConnectionFairy._checkout(self)
app_1      |   File "/usr/local/lib/python3.10/site-packages/sqlalchemy/pool/base.py", line 1271, in _checkout
app_1      |     fairy = _ConnectionRecord.checkout(pool)
app_1      |   File "/usr/local/lib/python3.10/site-packages/sqlalchemy/pool/base.py", line 719, in checkout
app_1      |     rec = pool._do_get()
app_1      |   File "/usr/local/lib/python3.10/site-packages/sqlalchemy/pool/impl.py", line 168, in _do_get
app_1      |     with util.safe_reraise():
app_1      |   File "/usr/local/lib/python3.10/site-packages/sqlalchemy/util/langhelpers.py", line 147, in __exit__
app_1      |     raise exc_value.with_traceback(exc_tb)
app_1      |   File "/usr/local/lib/python3.10/site-packages/sqlalchemy/pool/impl.py", line 166, in _do_get
app_1      |     return self._create_connection()
app_1      |   File "/usr/local/lib/python3.10/site-packages/sqlalchemy/pool/base.py", line 396, in _create_connection
app_1      |     return _ConnectionRecord(self)
app_1      |   File "/usr/local/lib/python3.10/site-packages/sqlalchemy/pool/base.py", line 681, in __init__
app_1      |     self.__connect()
app_1      |   File "/usr/local/lib/python3.10/site-packages/sqlalchemy/pool/base.py", line 905, in __connect
app_1      |     with util.safe_reraise():
app_1      |   File "/usr/local/lib/python3.10/site-packages/sqlalchemy/util/langhelpers.py", line 147, in __exit__
app_1      |     raise exc_value.with_traceback(exc_tb)
app_1      |   File "/usr/local/lib/python3.10/site-packages/sqlalchemy/pool/base.py", line 901, in __connect
app_1      |     self.dbapi_connection = connection = pool._invoke_creator(self)
app_1      |   File "/usr/local/lib/python3.10/site-packages/sqlalchemy/engine/create.py", line 636, in connect
app_1      |     return dialect.connect(*cargs, **cparams)
app_1      |   File "/usr/local/lib/python3.10/site-packages/sqlalchemy/engine/default.py", line 580, in connect
app_1      |     return self.loaded_dbapi.connect(*cargs, **cparams)
app_1      |   File "/usr/local/lib/python3.10/site-packages/psycopg2/__init__.py", line 122, in connect
app_1      |     conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
app_1      | sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) connection to server at "172.23.0.2", port 5432 failed: Connection timed out
app_1      |    Is the server running on that host and accepting TCP/IP connections?
app_1      | 
app_1      | (Background on this error at: https://sqlalche.me/e/20/e3q8)
zbq4xfa0

zbq4xfa01#

移动compose文件中的环境变量并连接到可路由的主机(0.0.0.0不是)

app:
    build:
      context: .
      dockerfile: Dockerfile
    depends_on:
      - db
    environment:
      DB_HOST: postgres  # matches 'container_name' of db container
      DB_PORT: "5432"

然后确保您使用的是

db_address = f'{os.environ.get("DB_HOST")}:{os.environ.get("DB_PORT")}'

相关问题