LoginSignup
5
0

とにかくシンプルなマイクロサービスをECS Service Connectで作る

Last updated at Posted at 2023-12-07

はじめに

こんにちは、GxPの杉山です。
こちらはグロースエクスパートナーズ Advent Calendar 2023の7日目の記事です。

個人開発中のプロダクトをマイクロサービスで開発をしており、その際にECS Service Connectを試しました。
その際にいくつかはまったので整理のため、とにかくシンプルなサンプルで記事を書きます。

なお、今回はterraformとgo echoのアプリを使用しています。

Terraform v1.5.2
go version go1.21.4

ソースはこちらです
https://github.com/Xmagnum2/service-connect-sample

システム構成は以下のようになっています。
image.png

セキュリティグループの設定

service-aとservice-bにはお互いのresource-groupを許可する設定を入れます。

resource "aws_security_group_rule" "a_from_b" {
  type                     = "ingress"
  from_port                = 8080
  to_port                  = 8080
  protocol                 = "tcp"
  source_security_group_id = aws_security_group.service_b.id
  security_group_id        = aws_security_group.service_a.id
}

resource "aws_security_group_rule" "b_from_a" {
  type              = "ingress"
  from_port         = 8081
  to_port           = 8081
  protocol          = "tcp"
  source_security_group_id = aws_security_group.service_a.id
  security_group_id = aws_security_group.service_b.id
}

*_from_anyは手元で確認する用なので別で確認する方法があれば必要ありません。

タスク定義

タスク定義のポートマッピングにECS Service Connect用の設定を追記します。

      portMappings = [
        {
          name          = "service_a"
          containerPort = 8080
          protocol      = "tcp"
          appProtocol   = "http"
        }
      ]

このnameがDNSとなります。

ECSサービス

ECSサービスにもservice_connect_configurationを追加します。

  service_connect_configuration {
    enabled = true
    service {
      client_alias {
        port = 80
      }
      port_name = "service_a"
    }

    namespace = aws_service_discovery_http_namespace.qiita.arn
  }

ここのポートは80である必要はありません。好きなポートを指定してokです。勝手に紐づいてくれます。

apply

今回は非常にシンプルな構成のためここまででECS Service Connectを利用する準備が整いました。
最後にterraform apply --var-file=env.tfvarsで実行するとリソースが作成されるため、goのコードをビルドしてecrへイメージをpushすれば疎通を確認することができるはずです!

serviceA
image.png
serviceB
image.png

まとめ

いかがだったでしょうか。
最初に概要を知って試したいとなったときにまずは動くものをっと思うのですが、ここまでシンプルな構成ってありそうであまりないんですよね。
同じような方の助けとなれば幸いです!

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