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?

ローカルの複数のDocker環境間でAPI連携をしてみた

Posted at

前提

  • Django:4.2
  • python:3.11
  • OS:22.04
  • Docker
  • WEBサーバー:nginx

やりたいこと

  • ローカルで開発中のアプリが二つあります(アプリAとアプリBとします)
  • 両アプリは別々のdockerコンテナで起動しています
  • アプリAで作成したAPIにアプリBから接続したい

コンテナ構成

DB(PostgreSQL)、Django、WEBサーバー(nginx)の3コンテナ

ポイント

  • 両アプリのコンテナを別々に作成しているため、アプリAで作成したAPIのURLに、アプリBからどのようなURLで接続すればいいか分からなかった
  • 各コンテナを同じDockerネットワーク上に接続すればいいらしい

コード

アプリA(API作成側)

docker-compose.yaml
networks:
    # qiita-networkというネットワークを作成し、そこに各コンテナを展開する
    qiita-network:
        name: qiita-network
        ipam:
            config:
                - subnet: xxx.yyy.zzz.0/20 # ネットワークのIPアドレスを固定するための記述

a-web:
    # buildやportsなどの処理
    networks:
        qiita-network:
            ipv4_address: xxx.yyy.zzz.1

# DjangoやDBのコンテナも作成。ipv4_addressは他コンテナと被らない値を設定する
urls.py
path('get-sample-records/', GetSampleRecords.as_view(), name='get-sample-records')
.env
ALLOWED_HOSTS=localhost,a-web # このwebがないとAPI接続時にエラーになる

GetSampleRecordsクラスは省略します

アプリB(API使用側)

docker-compose.yml
networks:
    qiita-network:
        name: qiita-network
        ipam:
            config:
                - subnet:xxx.yyy.zzz.0/20 # ネットワークのIPアドレスを固定するための記述

b-web:
    # buildやportsなどの処理
    networks:
        qiita-network:
            ipv4_address: xxx.yyy.zzz.2

# DjangoやDBのコンテナも作成。ipv4_addressは他コンテナと被らない値を設定する
Views.py
import requests

# アプリAのAPIに接続する
def fetch_api():
    response = requests.get('http://a-web/get-sample-records/')
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?