Python OpenAI library throws SSL certificate FileNotFoundError in Docker environment

I have a Python application that uses the OpenAI library running inside a Docker container. After I rebuilt my container image, it started throwing an SSL certificate error that wasn’t happening before.

Traceback (most recent call last):
  File "/app/script.py", line 8, in <module>
    ai_client = OpenAI(api_key=API_TOKEN)
  File "/usr/local/lib/python3.11/site-packages/openai/_client.py", line 123, in __init__
    super().__init__
  File "/usr/local/lib/python3.11/site-packages/openai/_base_client.py", line 860, in __init__
    self._client = http_client or SyncHttpxClientWrapper(
  File "/usr/local/lib/python3.11/site-packages/openai/_base_client.py", line 755, in __init__
    super().__init__(**kwargs)
  File "/usr/local/lib/python3.11/site-packages/httpx/_client.py", line 690, in __init__
    self._transport = self._init_transport(
  File "/usr/local/lib/python3.11/site-packages/httpx/_client.py", line 733, in _init_transport
    return HTTPTransport(
  File "/usr/local/lib/python3.11/site-packages/httpx/_transports/default.py", line 153, in __init__
    ssl_context = create_ssl_context(verify=verify, cert=cert, trust_env=trust_env)
  File "/usr/local/lib/python3.11/site-packages/httpx/_config.py", line 35, in create_ssl_context
    ctx = ssl.create_default_context(cafile=os.environ["SSL_CERT_FILE"])
  File "/usr/local/lib/python3.11/ssl.py", line 770, in create_default_context
    context.load_verify_locations(cafile, capath, cadata)
FileNotFoundError: [Errno 2] No such file or directory

Container setup:

FROM python:3.11-slim

WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY script.py .
ENTRYPOINT ["python", "script.py"]

Python code:

from openai import OpenAI

def main():
    API_TOKEN = "sk-****"
    ai_client = OpenAI(api_key=API_TOKEN)
    
if __name__ == "__main__":
    main()

Dependencies:

openai==1.56.2

The error seems to be related to SSL certificate verification but I’m not sure why it started happening now. Any ideas how to fix this?

I encountered a similar issue when transitioning to the python:3.11-slim image. It appears that the slim variants do not include CA certificates by default, which can lead to SSL verification errors, particularly with the newer OpenAI library’s stricter checks. To resolve this, you should modify your Dockerfile to install the ca-certificates package. Here’s an updated version:

FROM python:3.11-slim

RUN apt-get update && apt-get install -y ca-certificates && rm -rf /var/lib/apt/lists/*

WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY script.py .
ENTRYPOINT ["python", "script.py"]

This addition will ensure that SSL verification works as intended without compromising security.