LoginSignup
0
0

M1 MacでVSCodeを用いてCloud RunにFlaskのHello Worldアプリケーションをデプロイする方法

Posted at

このドキュメントでは、M1 Macを使用してVSCodeでFlaskのHello WorldアプリケーションをGoogle Cloud Runにデプロイする手順を説明します。

前提条件

  1. M1 Macを使用していること
  2. Google Cloudアカウントを持っていること
  3. Dockerとgcloud CLIがインストールされていること
  4. VSCodeがインストールされていること

手順

1. Google Cloudプロジェクトの作成

  1. Google Cloud Consoleにアクセスし、新しいプロジェクトを作成します。
  2. プロジェクトIDをメモしておきます。ここでは例としてhelloworld-projectとします。

2. Google Cloud SDKの設定

  1. Google Cloud SDKをインストールしていない場合は、インストール手順に従ってインストールします。
  2. ターミナルで以下のコマンドを実行して認証します。
gcloud auth login
gcloud config set project helloworld-project

3. Flaskアプリケーションの作成

  1. VSCodeを開き、新しいディレクトリを作成します。
mkdir flask-hello-world
cd flask-hello-world
  1. 必要なファイルを作成します。
app.py
from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, World!'

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8080)
requirements.text
Flask==2.0.3
gunicorn==20.1.0
Werkzeug==2.0.3
.dockerfile
# Use the official Python image from the Docker Hub
FROM python:3.9-slim

# Set the working directory
WORKDIR /app

# Copy the current directory contents into the container at /app
COPY . /app

# Install any needed packages specified in requirements.txt
RUN pip install --no-cache-dir -r requirements.txt

# Make port 8080 available to the world outside this container
EXPOSE 8080

# Run gunicorn when the container launches
CMD ["gunicorn", "--bind", "0.0.0.0:8080", "app:app"]

4. Dockerイメージのビルドとテスト

ターミナルで以下のコマンドを実行してDockerイメージをビルドします。
注意点として、M1MacではDockerイメージが、Cloud RunのLinux x86_64環境と互換性がないため、以下のコマンドを用いてビルドする必要があります。

docker buildx build --platform linux/amd64 -t flask-hello-world .

Dockerイメージをローカルでテストします。

docker run -p 8080:8080 flask-hello-world

ブラウザで http://localhost:8080 にアクセスし、"Hello, World!"が表示されることを確認します。

5. Dockerイメージのタグ付けとプッシュ

DockerイメージをGoogle Container Registryにタグ付けします。

docker tag flask-hello-world gcr.io/helloworld-project/helloworld

DockerイメージをGoogle Container Registryにプッシュします。

docker push gcr.io/helloworld-project/helloworld

6. Cloud Runにデプロイ

以下のコマンドを実行してCloud Runにデプロイします。

gcloud run deploy helloworld \
  --image gcr.io/helloworld-project/helloworld \
  --platform managed \
  --region us-central1 \
  --allow-unauthenticated

デプロイが成功したら、表示されたURLにアクセスしてアプリケーションが動作していることを確認します。

まとめ

これで、M1 Macを使用してVSCodeで作成したFlaskのHello WorldアプリケーションをGoogle Cloud Runにデプロイする手順は完了です。デプロイされたアプリケーションは、指定されたURLで公開されています。お疲れ様でした!

参考リンク

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0