如何配置Postgresql以在BitBucket管道中运行FastAPI测试

问题描述

我正在尝试为我正在处理的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的。我在做什么错了?

解决方法

根据我在this article中找到的内容,以下是代码段:

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

访问该服务

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

DATABASE_URL = os.getenv('DATABASE_URL', 'postgresql://[email protected]/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://[email protected]/postgres 
                    --add-host host.docker.internal:$BITBUCKET_DOCKER_HOST_INTERNAL boilerplate
                    /bin/bash -c /run-tests.sh