0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

WSL2のDocker上でPython

Last updated at Posted at 2025-03-05

Docker構築

今後何か作るにしても、Dockerの知識は役立つだろうと思い導入した。
Docker Desktopをインストールし、ダウンロード。WSL2に構築できるようにした。
※WSL2とubuntuはインストール済み

Docker Desktop「Settings」→「General」タブで「Use the WSL 2 based engine」にチェックが入っていることを確認し、「Resources」→「WSL Integration」を開き、Ubuntu(使用するディストリ名) にチェックを入れて有効化。次にDockerのバージョンを確認。

docker version

とりあえずこれで動きそう。
目標はdocker composeでの実行であるため、Docker Compose バージョン確認済。

docker compose version

Docker Composeを使用したコンテナ作成

docker-compose.ymlを作成。

version: "3.8"
services:
  web:
    image: nginx:alpine
    container_name: my-nginx
    ports:
      - "8080:80"

起動する。

docker compose up -d

Web ブラウザで http://localhost:8080/ にアクセスし、Nginx の Welcome ページが表示された。

Docker ComposeでのPython実行

簡単なコードだが、ディレクトリ構成。将来的にライブラリをインストールしたいので、Dockerfileを追加。

my_python_app/
├─ encoder.py
├─ requirements.txt
├─ Dockerfile
└─ docker-compose.yml

以下は内容。

・encoder.py

import base64
import sys

def str_to_base64(x):
    """文字列をbase64表現変換

    b64encode()はbyte-like objectを引数にとる
    文字列はencode()でbyte型にして渡す
    """
    return base64.b64encode(x.encode('utf-8'))

def main():
    target = sys.argv[1]
    print(str_to_base64(target))


if __name__ == "__main__":
    main()

・Dockerfile

FROM python:3.9-slim

# 作業ディレクトリを指定
WORKDIR /usr/src/app

# requirements.txt をコンテナにコピーしてpip install
COPY requirements.txt /usr/src/app/
RUN pip install --no-cache-dir -r requirements.txt

# ソースコードをコピー
COPY . /usr/src/app

# コンテナ起動時に実行するコマンド
CMD ["python", "encoder.py"]

・docker-compose.yml

version: "3.8"

services:
  python-app:
    build: .
    container_name: my-python-app

requirement.txtは今回は省略。

実際にコンテナを起動及び実行してみる。

docker compose build
docker compose run python-app python

WARNINGが出力されたが今回は無視している(いろいろ実行したためであると思われる)
結果は以下となった

b'cHl0aG9u'

今回はここまで。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?