ネットワークの設定

APIコンテナとDBコンテナが通信できるように、Dockerネットワークを作成して両方のコンテナを接続します。

1. ネットワークの作成

ノートアプリケーション用のネットワークを作成します。

docker network create note-network

ネットワークが作成されたことを確認します。

docker network ls

以下のようにnote-networkが表示されていれば成功です。

NETWORK ID     NAME           DRIVER    SCOPE
xxxxxxxxxxxx   note-network   bridge    local
xxxxxxxxxxxx   bridge         bridge    local
xxxxxxxxxxxx   host           host      local
xxxxxxxxxxxx   none           null      local

2. コンテナをネットワークに接続

既に起動しているコンテナを、作成したネットワークに接続します。

まず、DBコンテナを接続します。

docker network connect note-network db-container

次に、APIコンテナを接続します。

docker network connect note-network api-container

3. ネットワーク接続の確認

ネットワークの詳細を確認し、両方のコンテナが接続されていることを確認します。

docker network inspect note-network

以下のような出力結果が表示されます。Containersセクションに、db-containerとapi-containerの両方が表示されていれば、正しく接続されています。

[
    {
        "Name": "note-network",
        "Id": "a1b2c3d4e5f6...",
        "Created": "2026-01-15T10:00:00.000000000Z",
        "Scope": "local",
        "Driver": "bridge",
        "EnableIPv6": false,
        "IPAM": {
            "Driver": "default",
            "Options": {},
            "Config": [
                {
                    "Subnet": "172.18.0.0/16",
                    "Gateway": "172.18.0.1"
                }
            ]
        },
        "Internal": false,
        "Attachable": false,
        "Ingress": false,
        "ConfigFrom": {
            "Network": ""
        },
        "ConfigOnly": false,
        "Containers": {
            "abc123...": {
                "Name": "api-container",
                "EndpointID": "def456...",
                "MacAddress": "02:42:ac:12:00:03",
                "IPv4Address": "172.18.0.3/16",
                "IPv6Address": ""
            },
            "xyz789...": {
                "Name": "db-container",
                "EndpointID": "ghi012...",
                "MacAddress": "02:42:ac:12:00:02",
                "IPv4Address": "172.18.0.2/16",
                "IPv6Address": ""
            }
        },
        "Options": {},
        "Labels": {}
    }
]

4. API動作確認

ネットワーク接続が完了したら、APIからデータベースへの接続をテストします。

まず、ノートを1件作成します。

curl -X POST http://localhost:8000/notes \
  -H "Content-Type: application/json" \
  -d '{"title": "Docker Notes", "content": "Learning the basics of containers"}'

以下のようなレスポンスが返れば、ノートの作成に成功しています。

{"title":"Docker Notes","content":"Learning the basics of containers","id":1,"created_at":"2026-01-01T10:00:00","updated_at":"2026-01-01T10:00:00"}

次に、作成したノートを取得します。

curl http://localhost:8000/notes

先ほど作成したノートが取得できれば、APIコンテナからDBコンテナへの通信が正常に行われています。

[{"title":"Docker Notes","content":"Learning the basics of containers","id":1,"created_at":"2026-01-01T10:00:00","updated_at":"2026-01-01T10:00:00"}]