We will deploy a SPA (Single Page Application) on AWS S3 with CDN (Content Delivery Network) and HTTPS enabled.
For this project we will use the basic React project.
npx create-react-app ayudantia-front
npm run start
Now we will compile our SPA so it is client side rendered.
npm run build
- Go to S3
- Create bucket
- Name the bucket and uncheck all
Block all public access
checkboxes. - Go to your bucket
- In the
Properties
tab selectEdit
in theStatic Web Hosting
- Select
Enable
and change index document and error document toindex.html
- Go to
Permissions
tab andEdit
Bucket Policy
- Use the following policy (replace BUCKETARN with your Bucket Arn shown in the same view)
{ "Version": "2012-10-17", "Statement": [ { "Sid": "PublicReadGetObject", "Effect": "Allow", "Principal": "*", "Action": "s3:GetObject", "Resource": "BUCKETARN/*" } ] }
This steps are not necessary if you already have your access keys.
- Go to your Profile options in the top-right menu.
- Select
Security credentials
- Select
Create access key
and create the keys. - Save the keys (safely).
Follow these steps to install con configure.
- Install (only for Debian Based Systems) (If you are using Mac, use the link above)
curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip" unzip awscliv2.zip sudo ./aws/install
- Configure using the keys created in the previous step.
aws configure
- Build your project
npm build
- Upload the created build to your bucket
aws s3 sync build/ s3://BUCKET --delete
- Now your site is uploaded, go to your AWS console, S3, your bucket, Properties tab, and copy the url of the website in the bottom of the settings.
- Change your region in your AWS console to
us-east-1
- Go to
Certificate Manager
Request certificate
Request a public certificate
andNext
- Write all the domains that you want to use, ie.
domain.com
,*.domain.com
. - Create the certificate and add the records required to your DNS.
- Go to
Cludfront
Create a Cloudfront distribution
.- For the origin, use your S3 bucket url from S3 console in properties, static web hosting.
- In default cache behaviour, in Viewer protocol policy, select
Redirect HTTP to HTTPS
. - In Settings, Alternate Domain Name, write your domain name, ie.
domain.com
,*.domain.com
. - In the same Settings part, Custom SSL Certificate, select the created certificate.
Create distribution
- Go to your Cloudfront distribution and copy its Domain Name.
- Go to your DNS and create a CNAME with your custom domain/domains and your cloudfront distribution domain name as its value.
To update your frontend, you have to
- Build the changes
npm build
. - Upload the changes to your S3 bucket
aws s3 sync build/ s3://BUCKET --delete
. - Invalidate the cache in Cloudfront
aws cloudfront create-invalidation --distribution-id YOUR_CLOUDFRONT_ID --paths "/*"
- Check if the cache was invalidated
aws cloudfront get-invalidation --id INVALIDATION_ID --distribution-id DISTRIBUTION_ID
In this example, we are using S3 to deploy an SPA, static website or any static assets, but, why should we use S3?. We can, for example, use EC2 or another service and setup a webserver (such as NGINX) to serve static assets or our SPA, but S3 has some advantages such as:
- Pricing:
- Máquina propia (On premise): Demanda tener un computador/servidor corriendo 24/7 y podría fallar en casos de terremotos, incendios, etc. Presenta múltiples desafíos en los hay invertir para 'solucionar'.
- EC2: Se paga por:
- Arriendo de capacidad de procesamiento (CPU)
- Ram
- Disco duro fijo (Si uno usa 1GB, pero arrienga 50GB por la posibilidad de llegar a esa capacidad, se paga por los 50GB).
- Transferencia de datos. (Cada vez que alguien ingresa a nuestro sitio)
- Dirección IP
- Otros.
- S3: Se paga por:
- Disco duro utilizado (Es flexible según demanda)
- Existe la opción de pagar menos por espacio de memoria que se accede con menor frecuencia.
- Transferencia de datos
- Operaciones de BD (En caso de usar S3 como bdd NoSQL)
- Otros
- Throughput/Capacidad de acceso
- EC3:
- Depende de la configuración del usuario.
- En caso de necesitar más capacidad se debe escalar horizontal/verticalmente y configurar load balancers.
- S3
- Está optimizado para traspasar datos estáticos (sin necesitar alguna configuración propia). Con un solo S3 aseguran soportar 5500 request por segundo
- En caso de necesitas más capacidad, se puede utilizar Cloudfront como Content Delivery Network.
- EC3:
- Ease of use
- More info Here