ECS fargate

문학적인유사성·2023년 6월 29일
1

AWS

목록 보기
58/64
post-thumbnail

이미지 생성

python을 이용해 간단하게 플라스크 도커 이미지 만들기

Dockerfile

[root@ip-10-1-8-104 ecs]# cat Dockerfile
vi Dockerfile
FROM python:3.9-slim
COPY . /app
RUN pip3 install flask
WORKDIR /app
CMD ["python3", "-m", "flask", "run", "--host=0.0.0.0"]

app.py

[root@ip-10-1-8-104 ecs]# cat app.py
from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_yusa():
    return 'hello yusa!!!'

if __name__ == '__main__':
    app.run(debug=True)

도커 빌드후 ecr push

docker build -t yusapython:latest .
docker tag
docker push ${ECR repo}

AWS 콘솔로 생성

IAM Role 생성

ecsTaskExecutionRole이 없다면 생성
1. AmazonECSTaskExecutionRolePolicy 선택
2. 신뢰관계 설정

{
    "Version": "2008-10-17",
    "Statement": [
        {
            "Sid": "",
            "Effect": "Allow",
            "Principal": {
                "Service": "ecs-tasks.amazonaws.com"
            },
            "Action": "sts:AssumeRole"
        }
    ]
}

LB 생성 및 TG 생성

  1. Name 추가
  2. VPC 선택후 mappings에 subnet 기입 ( fargate가 올라올 서브넷 az모두 선택)
  3. SG선택 LB에 들어올때 붙는 SG
  • 80 0.0.0.0/0 http로 선택
  1. target group 생성
  • IP address 선택
  • HTTP 80 선택
  • register targets에 아무것도 기입하지않는다 ( 알아서 넣어줌 )
  1. 만든 TG선택하여 listenr에 추가

ECS 생성

  1. console에서 create cluster 생성
  2. vpc 선택
  3. subnet 선택
  • 나는 private 만 선택하였음, public에 노출되는 것을 원하지 않음
  1. Infrastructure에 fargate만 선택

Task Definitions 추가

  1. 이름 기입
  2. container-1 기입
  • 이름 넣기
  • Image URI는 ECR repo의 위치 기입
  • Port mapping 5000 넣기 (flask는 5000)
  • App env : AWS fargate
  • Linux/x86_64
  • 1vCPU, 3GB
  • Task Role : -
  • Task execution role : ecsTaskExecutionRole 선택

SVC 생성

  1. laucnh type으로 fargate고를수있고, capacity provider staregy로 고를수있는데, 그냥 fargate로만 돌리기
  2. Deployment configuration
  • Service
  • Family : Task definition에서 정의한 것 버전 선택
  • 이름 설정
  • 개수 설정

Networking

  1. vpc 설정
  2. subnet설정 ( private만 선택 )
  3. SG 설정 5000 허용
  • source를 LB SG, 5000, TCP로 선택

LB 설정

  1. alb 생성한 것 쓰겠음.
  2. listenr 생성한 것 쓰겠음
  3. TG 생성한 것 쓰겠음
  4. 생성

테라폼으로 생성

나는 테라폼이 좋더라...콘솔에서 생성하면 자꾸 오류가 생기고 설정 뭐 잘못한거 있고~
코드로 보면 한번에 보이니까 편해...

# locals
data "aws_iam_role" "ecs_task_execution_role" {
  name = "ecsTaskExecutionRole"
}

locals {
  vpc_id     = data.terraform_remote_state.vpc.outputs.vpc_id
  pub_subnet_ids = data.terraform_remote_state.vpc.outputs.public_subnets
  priv_subnet_ids = data.terraform_remote_state.vpc.outputs.private_subnets

  tags = merge(
    data.aws_default_tags.aws_dt.tags,
    { Owner = "yusa" }
    )
}



resource "aws_security_group" "lb" {
  name        = "ecs-test-yusa-alb-sg"
  vpc_id      = local.vpc_id

  ingress {
    protocol    = "tcp"
    from_port   = 80
    to_port     = 80
    cidr_blocks = ["0.0.0.0/0"]
  }

  egress {
    from_port = 0
    to_port   = 0
    protocol  = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

resource "aws_lb" "default" {
  name            = "ecs-test-yusa-lb"
  subnets         = local.pub_subnet_ids
  security_groups = [aws_security_group.lb.id]
}

resource "aws_lb_target_group" "hello_yusa" {
  name        = "ecs-test-yusa-target-group"
  port        = 80
  protocol    = "HTTP"
  vpc_id      = local.vpc_id
  target_type = "ip"
}

resource "aws_lb_listener" "hello_yusa" {
  load_balancer_arn = aws_lb.default.id
  port              = "80"
  protocol          = "HTTP"

  default_action {
    target_group_arn = aws_lb_target_group.hello_yusa.id
    type             = "forward"
  }
}

resource "aws_ecs_task_definition" "hello_yusa" {
  family                   = "hello-yusa-app"
  network_mode             = "awsvpc"
  requires_compatibilities = ["FARGATE"]
  cpu                      = 1024
  memory                   = 2048
  execution_role_arn       = "${data.aws_iam_role.ecs_task_execution_role.arn}" # for Using ECR

  container_definitions = <<DEFINITION
[
  {
    "image": "${계정번호}.dkr.ecr.us-east-1.amazonaws.com/test-ecr:latest",
    "cpu": 1024,
    "memory": 2048,
    "name": "hello-yusa-app",
    "networkMode": "awsvpc",
    "portMappings": [
      {
        "containerPort": 5000,
        "hostPort": 5000
      }
    ]
  }
]
DEFINITION
}


resource "aws_security_group" "hello_yusa_task" {
  name        = "ecs-test-yusa-task-security-group" # for flask
  vpc_id      = local.vpc_id

  ingress {
    protocol        = "tcp"
    from_port       = 5000
    to_port         = 5000
    security_groups = [aws_security_group.lb.id]
  }

  egress {
    protocol    = "-1"
    from_port   = 0
    to_port     = 0
    cidr_blocks = ["0.0.0.0/0"]
  }
}

resource "aws_ecs_cluster" "main" {
  name = "ecs-test-yusa-cluster"
}

resource "aws_ecs_service" "hello_yusa" {
  name            = "hello-yusa-service"
  cluster         = aws_ecs_cluster.main.id
  task_definition = aws_ecs_task_definition.hello_yusa.arn
  desired_count   = var.app_count
  launch_type     = "FARGATE"

  network_configuration {
    security_groups = [aws_security_group.hello_yusa_task.id]
    subnets         = local.priv_subnet_ids
  }

  load_balancer {
    target_group_arn = aws_lb_target_group.hello_yusa.id
    container_name   = "hello-yusa-app"
    container_port   = 5000
  }

  depends_on = [aws_lb_listener.hello_yusa]
}

결과

profile
유사 IT 항해

0개의 댓글