【问题标题】:How to configure postgresql to run FastAPI tests in BitBucket Pipelines如何配置 postgresql 以在 BitBucket Pipelines 中运行 FastAPI 测试
【发布时间】:2020-08-17 22:30:53
【问题描述】:

我正在尝试为我正在处理的 FastAPI 样板设置管道。到目前为止我失败了,我不知道为什么。这是我所拥有的:

bitbucket-pipelines.yml

image: python:3.7.4-slim-buster

options:
    max-time: 5

definitions: 
    steps:
        - step: &test
            name: test
            script:
                - >-
                    docker build -f {{cookiecutter.app_name}}/{{cookiecutter.service_name}}/tests.dockerfile
                    -t boilerplate ./{{cookiecutter.app_name}}/{{cookiecutter.service_name}}
                - >-
                    docker run --env POSTGRES_HOST=host.docker.internal 
                    --add-host host.docker.internal:$BITBUCKET_DOCKER_HOST_INTERNAL boilerplate
                    /bin/bash -c /run-tests.sh
            services:
                - docker
                - postgres
            caches:
                - docker
    services: 
        postgres: 
            image: postgres
            environment:
                POSTGRES_HOST_AUTH_METHOD: trust

pipelines:
    pull-requests:
        '**':
            - step: *test

我正在连接到我的数据库:

DATABASE_URL = os.getenv('DATABASE_URL', 'postgresql://postgres@localhost/postgres')

这是我在运行管道时遇到的错误:

E   sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) could not connect to server: Connection refused
E       Is the server running on host "localhost" (127.0.0.1) and acceptingE    TCP/IP connections on port 5432?
E   
E   (Background on this error at: http://sqlalche.me/e/13/e3q8)

我添加了postgresql://postgres@localhost/postgres,因为这就是 BitBucket 为默认用户设置 postgresql 的方式。我做错了什么?

【问题讨论】:

    标签: python-3.x postgresql bitbucket-pipelines fastapi


    【解决方案1】:

    根据我在this article 中找到的内容,这是一个 sn-p:

    如果您需要从 docker 中运行的服务与构建容器中运行的服务进行通信,请在启动服务时使用 --add-host host.docker.internal:$BITBUCKET_DOCKER_HOST_INTERNAL 为其提供以下主机条目然后,您可以使用 host.docker.internal:port 访问该服务

    我应该指定host.docker.internal 作为我的主机:

    DATABASE_URL = os.getenv('DATABASE_URL', 'postgresql://postgres@host.docker.internal/postgres')
    

    而不是使用localhost

    另一种方法是执行以下操作:

    DATABASE_URL = os.getenv('DATABASE_URL')
    

    那么不要做docker run --env POSTGRES_HOS=host.docker.internal,而是做:

    definitions: 
        steps:
            - step: &test
                name: test
                script:
                    ...
                    ...
                    - >-
                        docker run --env DATABASE_URL=postgresql://postgres@host.docker.internal/postgres 
                        --add-host host.docker.internal:$BITBUCKET_DOCKER_HOST_INTERNAL boilerplate
                        /bin/bash -c /run-tests.sh
    

    【讨论】:

      猜你喜欢
      • 2019-01-19
      • 2011-09-17
      • 2021-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-02
      相关资源
      最近更新 更多