-
Notifications
You must be signed in to change notification settings - Fork 4
feat: AWS Deploy docs #27
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
sarry20
wants to merge
9
commits into
ccsw-csd:master
Choose a base branch
from
sarry20:feat/aws-deploy
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
d9512c6
feat: starting deploy docs
sarry20 723d6cc
feat: starting ECS documentation
sarry20 c65f642
feat: ECS documentation
sarry20 1d78167
fix: broken hyperlink to docker
sarry20 18187f5
style: improve formatting
sarry20 362a13e
Merge branch 'master' of https://github.com/ccsw-csd/tutorial into fe…
sarry20 4001fc4
fix: Create ECR Repository
sarry20 412d973
feat: add suggestions
sarry20 ac08e3e
feat: add suggestions
sarry20 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,68 @@ | ||
| # Despligue en la nube | ||
|
|
||
|
|
||
| ## Que es Elastic Beanstalk | ||
| Para desplegar la aplicacion en AWS, utilizaremos el servicio AWS Elastic Beanstalk (AWS EB), permite migrar, implementar y escalar fácilmente aplicaciones full stack. Gestiona las operaciones de infraestructura y aplicaciones, lo que nos ayudará a centrarnos en la lógica de negocio. | ||
|
|
||
| Gracias a EB se podremos desplegar fácilmente todas nuestras aplicaciones haciendo uso de `docker` y `docker compose`, y así nos olvidamos de cualquier cambio de entorno. | ||
|
|
||
| ## Pre-requisitos | ||
| En este tutorial, partiremos de la aplicacion con [micro servicios](../springcloud/intro.md) y [dockerizada](../docker/installdocker.md). | ||
| Igual que vimos en [AWS CLI](./cli.md), instalaremos todo usando WSL. | ||
|
|
||
| ## Instalacion EB CLI | ||
| Para poder desplegar la aplicacion, primero necesitaremos la CLI de Elastic Beanstalk, para ello necesitamos unos pasos previos. | ||
|
|
||
|
|
||
| 1. Actualizar los paquetes de ubuntu. | ||
| ```bash | ||
| sudo apt update | ||
| sudo apt upgrade -y | ||
| ``` | ||
|
|
||
| 2. Instalar python. | ||
| ```bash | ||
| sudo apt install -y python3 pip pipx python-is-python3 | ||
| ``` | ||
|
|
||
| 3. Instalar virtualenv. | ||
| ```bash | ||
| sudo pipx install virtualenv | ||
| ``` | ||
|
|
||
| 4. Instalar EB CLI. | ||
| ```bash | ||
| git clone https://github.com/aws/aws-elastic-beanstalk-cli-setup.git | ||
| python ./aws-elastic-beanstalk-cli-setup/scripts/ebcli_installer.py | ||
| ``` | ||
|
|
||
| 5. Verificar que EB CLI se ha instalado correctamente. | ||
| ```bash | ||
| eb --version | ||
| ``` | ||
|
|
||
| ## Despligue de la aplicacion | ||
|
|
||
| Una vez instalada EB CLI, en la carpeta raiz donde esta nuestro docker compose y los proyectos, crearemos el contenedor en la nube y desplegaremos la aplicacion. | ||
|
|
||
| 1. Inicializar el proyecto. | ||
| ```bash | ||
| eb init -p docker docker-compose-tutorial --region eu-west-3 | ||
| ``` | ||
| 2. (Opcional) si queremos conectarnos a la instancia de EC2 por SSH, deberemos configurar un par de claves. | ||
| ```bash | ||
| eb init | ||
| ``` | ||
| Aparecerá un mensaje parecido a este, simplemente seleccionaremos que clave queremos usar. | ||
| ``` | ||
| Do you want to set up SSH for your instances? | ||
| (y/n): y | ||
| Select a keypair. | ||
| 1) my-keypair | ||
| 2) [ Create new KeyPair ] | ||
|
|
||
| ``` | ||
| 3. Creamos el entorno y desplegamos la aplicacion. | ||
| ```bash | ||
| eb create docker-compose-tutorial | ||
| ``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,267 @@ | ||
| # Despligue en la nube | ||
| Para desplegar la aplicacion haremos uso de los servicios de AWS Elastic Cluster Registry (AWS ECR) y Elastic Cluster Service (AWS ECS). | ||
|
|
||
| ## Que es Elastic Cluster Registry | ||
| Amazon Elastic Container Registry (Amazon ECR) es un registro de contenedores completamente administrado que ofrece alojamiento de alto rendimiento, lo que permite utilizar imágenes (docker) de aplicaciones y artefactos con la confianza de que funcionarán en cualquier lugar. | ||
|
|
||
| ECR nos permite tanto hacer repositorios privados como publicos para poder almacenar las imagenes, en este caso haremos uso de los repositorios privados para almacenar las imagenes de nuestros micro servicios. Este aspecto permite que las empresas puedan tener su propia lógica en AWS sin exponerla | ||
|
|
||
| ## Que es Elastic Cluster Service | ||
| Amazon ECS es un servicio de orquestación de contenedores completamente administrado que ayuda a implementar, administrar y escalar fácilmente las aplicaciones en contenedores. Se integra profundamente al resto de la plataforma de AWS para proporcionar una solución segura y fácil de utilizar que ejecuta cargas de trabajo con contenedores en la nube. | ||
|
|
||
| ## Pre-requisitos | ||
| En este tutorial, partiremos de la aplicacion con [micro servicios](../springcloud/intro.md), [dockerizada](../docker/installdocker.md) y de [AWS CLI](./cli.md) | ||
|
|
||
| ## Crear repositorios ECR | ||
| Para poder desplegar la aplicacion, primero necesitaremos crear los repositorios en AWS. | ||
|
|
||
| El primer paso de todos es autenticar nuestro docker para que pueda acceder a los repositorios para ello ejecutaremos el siguiente comando | ||
| ```bash | ||
| aws ecr get-login-password --region <region> | sudo docker login --username AWS --password-stdin <aws_account_id>.dkr.ecr.<region>.amazonaws.com | ||
| ``` | ||
|
|
||
| Donde `<region>` es la region que tengamos configurada, y `<aws_account_id>` lo deberemos tener configurado de nuestros credenciales de AWS | ||
|
|
||
| Ahora, para cada microservicio que queramos almacenar en ECR ejecutaremos los siguientes comandos. | ||
|
|
||
| 1. Crear el repositorio de ECR | ||
| ```bash | ||
| aws ecr create-repository repository-name | ||
| ``` | ||
|
|
||
| 2. Crear la imagen de docker. | ||
| ```bash | ||
| sudo docker build -t image:tag . | ||
| ``` | ||
|
|
||
| 1. Etiquetar la imagen para poder enviarla al repositorio | ||
| ```bash | ||
| sudo docker tag image:tag <aws_account_id>.dkr.ecr.<region>.amazonaws.com/remote-repository:tag | ||
| ``` | ||
|
|
||
| 1. Enviar la imagen al repositorio de AWS. | ||
| ```bash | ||
| sudo docker push <aws_account_id>.dkr.ecr.<region>.amazonaws.com/remote-repository:tag | ||
| ``` | ||
|
|
||
| ## Despligue de la aplicacion | ||
|
|
||
| Para el despliegue de la aplicacion, vamos a crear los ocho servicios en ECS y dos ALB (Application Load Balancer) para el eureka y el gateway. | ||
|
|
||
| Antes de crear los servicios necestiamos crear los ALB y el grupo de seguridad, vamos con ello | ||
|
|
||
| ### Crear grupo de seguridad compartido. | ||
|
|
||
| 1. Crear el grupo de seguridad que tendrán los ECS | ||
| ```bash | ||
| aws ec2 create-security-group --group-name ecs-microservices-sg --description "Shared SG for ECS microservices communication" --vpc-id <VPC_ID> --region <REGION> | ||
| ``` | ||
|
sarry20 marked this conversation as resolved.
|
||
|
|
||
| - `VPC` es el Virtual Prive Cloud. vendría a ser nuestra área de red en la nube con nuestros permisos, configuración específica y más detalles que podamos configurar | ||
|
|
||
| 2. Autorizar todas las peticiones a cualquier puerto entre los ECS del grupo de seguridad | ||
| ```bash | ||
| aws ec2 authorize-security-group-ingress --group-id <SG_SHARED> --protocol tcp --port 0-65535 --source-group <SG_SHARED> --region <REGION> | ||
|
sarry20 marked this conversation as resolved.
|
||
| ``` | ||
|
|
||
| - `SG_SHARED` será el grupo de seguridad que configuremos | ||
|
|
||
| 3. Exponer a internter el puerto del frontend para poder visitar la pagina | ||
| ```bash | ||
| aws ec2 authorize-security-group-ingress --group-id <SG_SHARED> --protocol tcp --port 4200 --cidr 0.0.0.0/0 --region <REGION> | ||
| ``` | ||
|
|
||
| 4. Exponer a internter el puerto de eureka para debug | ||
| ```bash | ||
| aws ec2 authorize-security-group-ingress --group-id <SG_SHARED> --protocol tcp --port 8761 --cidr 0.0.0.0/0 --region <REGION> | ||
| ``` | ||
|
|
||
| ### Crear ALB para eureka. | ||
|
|
||
| Se crea un ALB para eureka que permitirá a los microservicios acceder a eureka | ||
|
|
||
| 1. Crear el load balancer | ||
| ```bash | ||
| aws elbv2 create-load-balancer --name eureka-internal-alb --subnets <SUBNET_1> <SUBNET_2> <SUBNET_3> --security-groups <SG_SHARED> | ||
| --scheme internal --type application --ip-address-type ipv4 --region <REGION> | ||
| ``` | ||
|
|
||
| 2. Crear un target group para detectar si eureka está disponible | ||
| ```bash | ||
| aws elbv2 create-target-group --name eureka-tg --protocol HTTP --port 8761 --vpc-id <VPC_ID> --target-type ip | ||
| --health-check-path "/actuator/health" --health-check-interval-seconds 30 | ||
| --health-check-timeout-seconds 5 --healthy-threshold-count 2 --unhealthy-threshold-count 3 --region <REGION> | ||
| ``` | ||
|
|
||
| 3. Permitir al ALB recibir trafico en el puerto de eureka y redigirilo al target group | ||
| ```bash | ||
| aws elbv2 create-listener --load-balancer-arn <EUREKA_ALB_ARN> --protocol HTTP --port 8761 --default-actions Type=forward,TargetGroupArn=<EUREKA_TG_ARN> --region <REGION> | ||
| ``` | ||
|
|
||
| ### Crear ALB para gateway. | ||
|
|
||
| Se crea un ALB para que el gateway sea accesible desde internet y poder hacer las peticiones desde el frontend al backend | ||
|
|
||
| 1. Crear un grupo de seguridad | ||
| ```bash | ||
| aws ec2 create-security-group --group-name alb-sg --description "ALB security group" --vpc-id <VPC_ID> | ||
| ``` | ||
|
|
||
| 2. Permitir el trafico http al puerto 80 desde internet | ||
| ```bash | ||
| aws ec2 authorize-security-group-ingress --group-id <SG_ALB> --protocol tcp --port 80 --cidr 0.0.0.0/0 | ||
| ``` | ||
|
|
||
| 3. Autorizar las peticiones entre el grupo de seguridad del ALB de gateway y entre el grupo de seguridad compartido | ||
| ```bash | ||
| aws ec2 authorize-security-group-ingress --group-id <SG_SHARED> --protocol tcp --port 8080 --source-group <SG_ALB> --region <REGION> | ||
|
sarry20 marked this conversation as resolved.
|
||
| ``` | ||
|
|
||
| - `SG_ALB` será nuestro Application Load Balancer | ||
|
|
||
| 4. Crear el load balancer | ||
| ```bash | ||
| aws elbv2 create-load-balancer --name gateway-alb --subnets <SUBNET_1> <SUBNET_2> <SUBNET_3> --security-groups <SG_ALB> --scheme internet-facing --type application --ip-address-type ipv4 | ||
| ``` | ||
|
|
||
| 5. Crear el target group para detectar si el servicio esta funcionando | ||
| ```bash | ||
| aws elbv2 create-target-group --name gateway-tg --protocol HTTP --port 8080 --target-type ip --vpc-id <VPC_ID> --health-check-path /actuator/health --health-check-interval-seconds 30 | ||
| --health-check-timeout-seconds 5 --healthy-threshold-count 2 --unhealthy-threshold-count 3 --matcher HttpCode=200 --region <REGION> | ||
| ``` | ||
|
|
||
| 6. Permitir el acceso publico y enrutar al gateway | ||
| ```bash | ||
| aws elbv2 create-listener --load-balancer-arn <GATEWAY_ALB_ARN> --protocol HTTP --port 80 --default-actions Type=forward,TargetGroupArn=<GATEWAY_TG_ARN> | ||
| ``` | ||
|
|
||
| ### Crear las tareas y los servicios | ||
|
|
||
| Por ultimo, ya solo queda crear las tareas que seran las que se ejecutaran en el ECS | ||
|
|
||
| 1. Crear el cluster que contendrá todos los servicios de ECS | ||
| ```bash | ||
| aws ecs create-cluster --cluster-name docker-deploy --region <REGION> | ||
| ``` | ||
|
|
||
| 2. Crear el rol de IAM que ejecutará los ECS | ||
| ```bash | ||
| aws iam create-role --role-name ecs-service-role --assume-role-policy-document '{ | ||
| "Version": "2012-10-17", | ||
| "Statement": [ | ||
| { | ||
| "Effect": "Allow", | ||
| "Principal": { | ||
| "Service": "ecs.amazonaws.com" | ||
| }, | ||
| "Action": "sts:AssumeRole" | ||
| } | ||
| ] | ||
| }' | ||
|
|
||
| ``` | ||
|
|
||
| 3. Asignar el permiso | ||
| ```bash | ||
| aws iam attach-role-policy --role-name ecs-service-role --policy-arn arn:aws:iam::aws:policy/service-role/AmazonECSServiceRolePolicy | ||
| ``` | ||
|
|
||
| Ahora para crear cada servicio tendremos que ejecutar estos mismos pasos. | ||
|
|
||
| 1. Crear el grupo de logs para almacenar en CloudWatch | ||
| ```bash | ||
| aws logs create-log-group --log-group-name /ecs/docker-deploy-<SERVICE> --region <REGION> | ||
| ``` | ||
|
|
||
| 2. Crear el JSON con la tarea | ||
| ```json | ||
| { | ||
| "family": "docker-deploy-<SERVICE>", | ||
| "containerDefinitions": [ | ||
| { | ||
| "name": "Main", | ||
| "image": "<AWS_ACCOUNT_ID>.dkr.ecr.<REGION>.amazonaws.com/<REPOSITORY>:<TAG>", | ||
| "cpu": 2048, | ||
| "memory": 4096, | ||
| "portMappings": [ | ||
| { | ||
| "containerPort": "<SERVICE_PORT>", | ||
| "protocol": "tcp" | ||
| } | ||
| ], | ||
| "essential": true, | ||
| "environment": [ | ||
| { | ||
| "name": "EUREKA_CLIENT_SERVICEURL_DEFAULTZONE", | ||
| "value": "http://<EUREKA_ALB_DNS>:8761/eureka/" | ||
| } | ||
| ], | ||
| "logConfiguration": { | ||
| "logDriver": "awslogs", | ||
| "options": { | ||
| "awslogs-group": "/ecs/docker-deploy-<SERVICE>", | ||
| "awslogs-region": "<REGION>", | ||
| "awslogs-stream-prefix": "ecs" | ||
| } | ||
| }, | ||
| "healthCheck": { | ||
| "command": [ | ||
| "CMD-SHELL", | ||
| "curl -f http://localhost:<SERVICE_PORT>/actuator/health || exit 1" | ||
| ], | ||
| "interval": 30, | ||
| "timeout": 5, | ||
| "retries": 3, | ||
| "startPeriod": 60 | ||
| } | ||
| } | ||
| ], | ||
| "requiresCompatibilities": [ | ||
| "FARGATE" | ||
| ], | ||
| "cpu": "2048", | ||
| "memory": "4096", | ||
| "networkMode": "awsvpc", | ||
| "executionRoleArn": "arn:aws:iam::<AWS_ACCOUNT_ID>:role/<EXECUTION_ROLE_NAME>", | ||
| "runtimePlatform": { | ||
| "cpuArchitecture": "X86_64", | ||
| "operatingSystemFamily": "LINUX" | ||
| } | ||
| } | ||
| ``` | ||
|
|
||
| 3. Crear la tarea que ejecutará el servicio | ||
| ```bash | ||
| aws ecs register-task-definition --cli-input-json file://task-ecs.json | ||
| ``` | ||
|
|
||
| 4. Crear el servicio | ||
|
|
||
| 4.1 Para los microservicios | ||
| ```bash | ||
| aws ecs create-service --cluster docker-deploy --service-name <SERVICE> --task-definition <TASK_NAME> --desired-count 1 --launch-type FARGATE | ||
| --network-configuration "awsvpcConfiguration={subnets=[<SUBNET_1>,<SUBNET_2>,<SUBNET_3>],securityGroups=[<SG_SHARED>],assignPublicIp=ENABLED}" | ||
| ``` | ||
|
|
||
| 4.2 Para eureka añadir al comando el siguiente flag | ||
| ```bash | ||
| --load-balancers "targetGroupArn=<EUREKA_TG_ARN>,containerName=Main,containerPort=8761" | ||
| ``` | ||
|
|
||
| 4.3 Para gateway añadir al comando el siguiente flag | ||
| ```bash | ||
| --load-balancers "targetGroupArn=<GATEWAY_TG_ARN>,containerName=Main,containerPort=8080" | ||
| ``` | ||
|
|
||
| ## Demostración | ||
|
|
||
| Una vez realizados todos los pasos podremos acceder tanto al frontend como al gateway como al eureka si asi lo hemos configurado | ||
|
|
||
| Frontend: | ||
|  | ||
|
|
||
| Gateway: | ||
|  | ||
|
|
||
| Eureka: | ||
|  | ||
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.