【CloudRun for Anthos】Dockerfileの設定とソースの内容をちゃんと合わせる

デプロイしたアプリがちゃんと起動しなくて、どうもDockerfileの中身がちゃんとわかってないのがいけなかったっぽいので、ちゃんとしたいと思います。

# Use the official lightweight Python image.
# https://hub.docker.com/_/python
FROM python:3.10-slim

# Allow statements and log messages to immediately appear in the Knative logs
ENV PYTHONUNBUFFERED True

# Copy local code to the container image.
ENV APP_HOME /app
WORKDIR $APP_HOME
COPY . ./

# Install production dependencies.
RUN pip install --no-cache-dir -r requirements.txt

# Run the web service on container startup. Here we use the gunicorn
# webserver, with one worker process and 8 threads.
# For environments with multiple CPU cores, increase the number of workers
# to be equal to the cores available.
# Timeout is set to 0 to disable the timeouts of the workers to allow Cloud Run to handle instance scaling.
CMD exec gunicorn --bind :$PORT --workers 1 --threads 8 --timeout 0 main:app

こちらから引っ張ってきたDockerfileのサンプルを何も考えずそのまま使っていたんですが、思うように動かなかったので、エラーの原因と対処をまとめておきます。

1:gunicornがないって言われて起動しない

Dockerfileの最後で「gunicornを起動するぞ~」って言ってるので、gunicornが無いとエラーになります。
gunicornなんて使ってないのになんで無いって怒られんのかな……って思ってたんですがここで使ってました。
requirements.txtにgunicornを追記すれば動くようになります。

2・gunicornがmainモジュールがないって言ってる

Buildは通った、デプロイもできた、でもなんか無限に再起動してる、って時に、エラーの内容を確認して、「mainがありません」と言われたら。

Dockerfileの最後のgunicorn起動コマンドで「main」を起動するよーって設定しているので、flaskのapp.run()コマンドが書いてあるファイルのファイル名は「main.py」にする。(もしくはgunicornの起動コマンドの方を変える)


この記事が気に入ったらサポートをしてみませんか?