DEV Community

Peter Johnson
Peter Johnson

Posted on

Host a Website on AWS EC2 Instance

Through this blog I'll provide a step-by-step guide through which you can host your static website on an AWS EC2 Instance.

So the services that we'll using are EC2 Instance and S3 Bucket (Used to store the code files).

1. The first step is to create an S3 bucket

Couple of important things to note are:
  • The bucket name is required to be unique and if you are planning to connect a domain name make sure your domain & bucket name are the same.
  • Also make sure you uncheck Block all public access otherwise the bucket won't be accessible.

Image

2. The next step is upload the code files

Inside the bucket click on the upload button and upload the respective code files onto the bucket.

3. Change permission

In order for the bucket to be accessible we also need to make a change in the the permission section by modifying the bucket policy with the following code:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "PublicRead",
            "Effect": "Allow",
            "Principal": "*",
            "Action": [
                "s3:GetObject",
                "s3:GetObjectVersion"
            ],
            "Resource": [
                "arn:aws:s3:::DOC-EXAMPLE-BUCKET/*"
            ]
        }
    ]
}
Enter fullscreen mode Exit fullscreen mode

Here you need to replace DOC-EXAMPLE-BUCKET with your bucket name.

4. Now it's time to create an EC2 Instance

I've created a basic instance within the free-tier eligibility.

Image

5. Connecting to the instance

The connection with instance is established using ssh, you can use the following command and replace the IP with your respective IP and Key.

ssh -i "peterawsjan.pem" ec2-user@18.221.22.171
Enter fullscreen mode Exit fullscreen mode

6. Setting up the web server

First of all let's grab the sudo permission by entering

sudo su
Enter fullscreen mode Exit fullscreen mode

Now its time to set things up, our EC2 Instance will act as an Server so for that we install httpd.

yum install httpd
Enter fullscreen mode Exit fullscreen mode

Image

Now that's done we need to pull data from our S3 bucket to the html folder of our Instance for that lets change directory.

cd  /var/www/html/
Enter fullscreen mode Exit fullscreen mode

To fetch data from S3 bucket we need the object url which can be found in index.html file in the S3 section of the AWS console.

wget "your object URL"
Enter fullscreen mode Exit fullscreen mode

Once you fetch it the type will be .zip and you need to unzip and move

uzip "your folder name"
mv "your folder name"* .
Enter fullscreen mode Exit fullscreen mode
That's it now its time to start our server.
service httpd.service
Enter fullscreen mode Exit fullscreen mode

You can access your hosted website by searching your Instances IP address.

I really hope this blog helped you host your website using EC2 Instance, Thank you.

Top comments (0)