docker 如何在Google Cloud Platform中正确设置API密钥?

sdnqo3pr  于 2023-06-21  发布在  Docker
关注(0)|答案(1)|浏览(192)

我正在尝试在GCP中部署一个需要OpenAI API密钥的项目。我在云shell终端将API key设置为环境变量,如下所示:

export OPENAI_API_KEY='sh-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

我可以使用Python访问它,如你所见:

然而,在我构建项目的docker镜像并尝试运行它之后,它给出了以下错误:

$ docker run app
[nltk_data] Downloading package punkt to /root/nltk_data...
[nltk_data]   Unzipping tokenizers/punkt.zip.
Traceback (most recent call last):
  File "/app/app.py", line 9, in <module>
    os.environ['OPENAI_API_KEY'] = os.getenv("OPENAI_API_KEY")
  File "/usr/local/lib/python3.9/os.py", line 684, in __setitem__
    value = self.encodevalue(value)
  File "/usr/local/lib/python3.9/os.py", line 756, in encode
    raise TypeError("str expected, not %s" % type(value).__name__)
TypeError: str expected, not NoneType

那么,这里有什么问题吗?
如果我这样做,我不会得到任何错误:

$ python
Python 3.9.2 (default, Feb 28 2021, 17:03:44) 
[GCC 10.2.1 20210110] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.environ['OPENAI_API_KEY'] = os.getenv("OPENAI_API_KEY")
>>>

所以我不明白为什么在运行docker镜像时会出现这个错误。

7nbnzgx9

7nbnzgx91#

Docker不能访问主机环境变量。您需要通过-e|--env将它们传递到docker run调用中。你可以试试:

docker run -e OPENAI_API_KEY='sh-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' app

docker run -e OPENAI_API_KEY="$OPENAI_API_KEY" app

相关问题