LoginSignup
5
3

More than 3 years have passed since last update.

VS Code Remote DevelopmentとDocker-ComposeとFastAPI

Posted at

1. VS Codeの設定

1.extentions から「Remote Development」をインストールする
image.png

2. DockerとFastAPIの作成

ディレクトリ構成図

.
├── docker-compose.yml
├── Dockerfile
├── main.py
└── requirements.txt 
Dockerfile
FROM python:3.8-alpine

WORKDIR /workspace

COPY requirements.txt .

RUN apk add --no-cache build-base \
 && pip install --no-cache-dir --trusted-host pypi.python.org -r requirements.txt \
 && apk del build-base

COPY main.py .

EXPOSE 8080

docker-compose.yml
version: "3.0"

services:
  api:
    container_name: "fastapi_app"
    build: .
    image: fastapi
    restart: always
    tty: true
    ports:
      - 8080:8080
requirements.txt
fastapi
uvicorn[standard]
main.py
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class User(BaseModel):
    user_id: int
    name: str

@app.get("/")
def read_root():
    return {"Hello": "World"}

@app.post("/user/")
def create_user(user: User):
    return {"res": "ok", "ID": user.user_id, "名前": user.name}

3. devcontainer を作成

  1. 左下の「Open a Remote Window」をクリックして、「Remote-container: Add Development Container Configuration Files...」を選択する
    image.png

  2. docker-compose.yml からVS Codeの設定ファイルを作成する為「From 'docker-compose.yml'」を選択する
    image.png

  3. 拡張機能をコンテナにインストールする為、.devcontainer/devcontainer.json の extensions に 「ms-python.python」 の拡張機能を指定する

devcontainer.json
{
"extensions": [
        "ms-python.python"
    ]
}

コンテナを起動

  1. 左下の「Open a Remote Window」をクリックして、「Remote-Containers: Open Folder in Container」を選択する image.png

FastAPIサーバーを起動

uvicorn main:app --reload --host 0.0.0.0 --port 8000

image.png

動作確認

参照

5
3
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
5
3