无法在新 docker 容器上安装 psycopg2-binary

Failing to install psycopg2-binary on new docker container

我在尝试 运行 我的 django 项目到新的 Docker 容器时遇到了问题。 这是我第一次使用 Docker,我似乎无法找到在其上 运行 一个 django 项目的好方法。尝试了多个教程后,我总是收到有关未安装 psycopg2 的错误。

requirements.txt:

-i https://pypi.org/simple
asgiref==3.2.7
django-cors-headers==3.3.0
django==3.0.7
djangorestframework==3.11.0
gunicorn==20.0.4
psycopg2-binary==2.8.5
pytz==2020.1
sqlparse==0.3.1

Docker文件:

# pull official base image
FROM python:3.8.3-alpine

# set work directory
WORKDIR /usr/src/app

# set environment variables
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

# install dependencies
RUN pip install --upgrade pip

COPY ./requirements.txt .
RUN pip install -r requirements.txt

# copy project
COPY . .

# set project environment variables
# grab these via Python's os.environ
# these are 100% optional here

ENV PORT=8000
ENV SECRET_KEY_TWITTER = "***"

在 运行ning docker-compose 构建时,出现以下错误:

Error: pg_config executable not found.

pg_config is required to build psycopg2 from source. Please add the directory

containing pg_config to the $PATH or specify the full executable path with the

option:

python setup.py build_ext --pg-config /path/to/pg_config build ...

or with the pg_config option in 'setup.cfg'.

If you prefer to avoid building psycopg2 from source, please install the PyPI

'psycopg2-binary' package instead.

我很乐意回答任何可能导致解决方案的问题。 另外,也许有人可以向我推荐一个关于 dockerizing django apps 的好教程?

在 Alpine Linux 上,您将需要编译所有包,即使 PyPI 上有预编译的二进制轮。在基于 Linux 的标准图像上,您不会(https://pythonspeed.com/articles/alpine-docker-python/ - 我在那里写的其他文章可能会有帮助,例如关于安全性的文章)。

因此,将您的基本图像更改为 python:3.8.3-slim-busterpython:3.8-slim-buster,它应该可以工作。

我用

制作了一张自定义图片
FROM python:alpine
ADD requirements.txt /
RUN apk update --no-cache \
&& apk add build-base postgresql-dev libpq --no-cache --virtual .build-deps \
&& pip install --no-cache-dir --upgrade pip \
&& pip install --no-cache-dir -r /requirements.txt \
&& apk del .build-deps
RUN apk add postgresql-libs libpq --no-cache

和requirements.txt

django
djangorestframework
psycopg2-binary

我成功了。这是代码:

FROM python:3.8.3-slim #Image python:3.9.5-slim also works # Image python:3.9.5-slim-buster also works

RUN apt-get update \
    && apt-get -y install libpq-dev gcc \
    && pip install psycopg2
    

此脚本适用于 MacBook Air M1

Docker 文件

FROM ubuntu:20.04
RUN apt-get update && apt-get -y install libpq-dev gcc && pip install psycopg2
COPY requirements.txt /cs_account/
RUN pip3 install -r requirements.txt

requirements.txt

psycopg2-binary~=2.8.6

根据 Zoltán Buzás 的回答更新了答案

这对我有用。试试瘦身形象。

在你的Dockerfile

FROM python:3.8.7-slim-buster

并在您的 requirements.txt 文件中

psycopg2-binary~= <<version_number>>