Blog

Amazon EC2 Tutorial

Key Takeaways

  • Amazon EC2 provides configurable virtual servers; AWS is the broader cloud platform that includes EC2 and other services.
  • Choose an instance family for your workload, then size it using CPU, memory, storage, and network measurements.
  • On-Demand, Spot, Savings Plans, and Reserved Instances solve different cost problems; a discount does not necessarily reserve capacity.
  • You can deploy a Java JAR directly on EC2 with systemd, or use Elastic Beanstalk to manage deployment resources.
  • Budget for storage, public IPv4, networking, and monitoring—not just the instance.

Amazon Elastic Compute Cloud, or EC2, lets you rent and configure virtual servers called instances. This Amazon EC2 tutorial explains instance selection and pricing, then walks through deploying a Java web application on Amazon Linux 2023.

You'll build a small executable JAR, upload it, and run it as a supervised service. The example is a restricted-access learning deployment, not a complete production architecture.

What Is Amazon EC2?

An EC2 instance gives you control over its operating system and installed applications without requiring you to maintain physical hardware. An Amazon Machine Image, or AMI, supplies the starting software configuration; an instance type determines the available compute resources. AWS's EC2 getting-started guide introduces these components.

The Difference Between AWS and EC2

AWS is the cloud platform. EC2 is one compute service within it, alongside services with different operational models, including S3 object storage, Lambda functions, and RDS managed databases. Don't treat those services as EC2 instances you administer.

Why Cloud?

Scalability

You can select a larger instance or distribute work across multiple instances. Neither happens automatically just because you use EC2: you must configure scaling policies and design the application to support them.

Cost Savings

Renting capacity avoids buying servers upfront, but cloud hosting isn't automatically cheaper. Idle resources, oversized instances, and network charges can erase the savings. Measure before making long-term commitments.

Security

Under AWS's shared responsibility model for EC2, AWS protects the underlying infrastructure. You're responsible for guest operating-system patches, application software, credentials, IAM permissions, and network-access configuration.

Availability

Availability Zones are isolated locations within a Region. A multi-AZ deployment can improve fault tolerance within that Region; geographic distribution across Regions is a separate design involving routing, replication, and recovery decisions.

Advertisement

How Is EC2 Used?

Typical workloads include web applications, background workers, build servers, game servers, rendering, and databases you choose to administer yourself. Use EC2 when operating-system control matters; consider a managed service when you don't need that control.

How Does EC2 Work?

You launch an AMI into a subnet within a virtual private cloud, or VPC—your AWS virtual network. You also choose storage, security groups that filter network traffic, and optionally an IAM instance profile that supplies an AWS role to the machine.

Access requires a working network path and an authorized connection method, not simply a running instance. Compatible AMIs include Linux distributions and Windows Server; the image, processor architecture, and instance type must work together.

Amazon EC2 Instance Types

A family identifies a resource profile; a size identifies its capacity. In t3.micro, t3 is the family and micro is the size. Consult the EC2 instance-type specifications for architecture, storage, networking, and Regional availability.

General Purpose

M families, such as M8i and M8g, balance compute, memory, and networking. Burstable T families, such as T3 and T4g, suit workloads with intermittent CPU demand, including small development servers.

Compute Optimized

C families, such as C8i and C8g, suit CPU-heavy work. Consider them for compilation, scientific calculations, and application workers whose CPU remains busy.

Memory Optimized

R families, such as R8i and R8g, suit memory-heavy applications, caches, and in-memory databases. Measure the complete process footprint, not just the Java heap.

Accelerated Computing

Families such as G6 provide GPUs for workloads including graphics and rendering. Choose hardware supported by your software and drivers rather than assuming a GPU improves an ordinary web application.

Storage Optimized

Families such as I7i target demanding local-storage workloads. Evaluate input/output operations per second, or IOPS, throughput, and data durability separately.

How to Choose a Family and Size

  • Match the AMI, Java runtime, and native dependencies to x86-64 or Arm. T4g uses Arm; T3 uses x86-64.
  • Load-test representative requests and measure latency, CPU, memory, disk activity, and network throughput.
  • Check instance-level network and EBS limits as well as vCPU count.
  • Understand T-family CPU credits: they govern bursting above baseline performance. Standard mode limits sustained bursting when credits run out; Unlimited mode can incur surplus-credit charges.

EC2 Pricing: Choose the Right Purchasing Option

For ordinary Linux On-Demand instances, compute is billed per second with a 60-second minimum. Billing rules vary by platform and product, so use the current EC2 On-Demand pricing page for your configuration.

OptionWhat you're buyingBest starting use
On-DemandCompute without a long-term commitmentLearning, experiments, uncertain demand
SpotInterruptible spare EC2 capacityRetryable workers and checkpointed batch jobs
Savings PlansA usage discount for an hourly spending commitmentMeasured, predictable baseline usage
Reserved InstancesA billing discount for matching instance usageStable configurations with understood commitment requirements
Dedicated HostsA physical host dedicated to your useSpecific licensing or host-placement requirements

Spot Instances and Interruptions

Spot depends on spare capacity and can be interrupted. AWS provides best-effort interruption notices, normally two minutes before stopping or termination; hibernation begins immediately. Checkpoint progress and make retries safe rather than relying on receiving a warning.

Savings Plans, Reserved Instances, and Capacity Reservations

Compute Savings Plans can follow eligible usage across EC2 families and Regions; EC2 Instance Savings Plans constrain the commitment to a family within a Region. Both exchange commitment for discounted usage, not reserved capacity.

Reserved Instances have one- or three-year terms, with No Upfront, Partial Upfront, and All Upfront payment options. Standard and Convertible offerings differ in modification and exchange flexibility.

Regional Reserved Instances don't reserve capacity; zonal Reserved Instances include a capacity benefit. On-Demand Capacity Reservations reserve capacity in a particular Availability Zone and don't themselves provide a discount. Decide separately whether you need lower prices, assured capacity, or both.

Dedicated Hosts

Dedicated Hosts provide host-level placement visibility and control and can support eligible software-license requirements. They don't, by themselves, establish regulatory compliance.

Free Tier and Cost Controls

Don't assume t2.micro, or any instance, is universally free. AWS changed its new-customer Free Tier program on July 15, 2025; account date, plan, credits, and eligibility matter. Check the current AWS Free Tier terms before launching.

Estimate compute, EBS, snapshots, data transfer, public IPv4, and any load balancer or NAT gateway in the AWS Pricing Calculator. Configure AWS Budgets notifications; notifications can be delayed and aren't a hard spending cap.

EC2 Storage and Instance Lifecycle

EBS volumes provide block storage that survives an instance stop/start cycle. On termination, each volume's DeleteOnTermination setting determines whether it is deleted. Take snapshots and test restores for data you need to retain.

Instance store is temporary local storage: its data is lost when the instance stops or terminates. Don't make it the only copy of important data.

Stopping an EBS-backed instance stops its running-instance compute charges, but EBS and retained Elastic IP addresses can continue costing money. An automatically assigned public IPv4 address is normally released on stop and replaced on start.

EC2 Tutorial: Host a Java Web Application on AWS

This walkthrough uses a new Amazon Linux 2023 x86-64 instance in us-east-1, a local JDK 25 installation, and a Bash terminal with SSH, SCP, and curl. Run local commands on your computer and server commands inside SSH as indicated.

Manually Deploying Your Java Application to EC2

1) Start the Instance Launch Workflow

In the EC2 console, select us-east-1, choose Launch instance, and name it ec2-java-tutorial. Review estimated charges before confirming the launch.

2) Choose the AMI

Select the current AWS-provided Amazon Linux 2023 x86-64 AMI. Amazon Linux 2 reached end of life on June 30, 2026; don't start this tutorial on AL2.

3) Select an Instance Type

Use t3.micro for this tiny demonstration, subject to availability and your account's eligibility. Select Standard CPU-credit mode to avoid surplus-credit billing; this isn't a sizing recommendation for a real Java application.

4) Configure Networking and Storage

Use an existing default VPC and public subnet, or create equivalent networking. Verify the complete public internet path:

  • The VPC has an attached internet gateway.
  • The subnet's route table sends 0.0.0.0/0 to that gateway.
  • Public IPv4 assignment is enabled for this instance.
  • A dedicated security group allows inbound TCP 22 and TCP 8080 only from your current public IPv4 address with a /32 suffix.
  • Outbound access permits the package downloads needed below; subnet network ACLs must also permit the connections.

For example, an SSH rule is TCP 22, source YOUR_PUBLIC_IPV4/32—not 0.0.0.0/0. Use an encrypted EBS root volume and review its delete-on-termination setting. If these networking terms are unfamiliar, read our AWS VPC tutorial first.

5) Create a Key Pair

Create a key pair named ec2-tutorial, download its PEM private key, and keep it private. Finish launching the instance and wait for its status checks to pass.

6) Connect Through SSH

On your computer, adjust the key path if necessary and enter the instance's public IPv4 address when prompted. Follow AWS's SSH connection prerequisites, including verifying the host fingerprint.

KEY="$HOME/Downloads/ec2-tutorial.pem"
chmod 400 "$KEY"
read -r -p "EC2 public IPv4 address: " EC2_HOST
ssh -i "$KEY" "ec2-user@$EC2_HOST"

7) Install Java on Amazon Linux 2023

AL2023 uses DNF package management, not the AL2 Extras workflow. Install the supported Corretto 25 headless package on the instance:

sudo dnf install -y java-25-amazon-corretto-headless

8) Verify the Runtime

java -version

Confirm that the output identifies Corretto 25. As of October 17, 2026, Java 25 is the latest LTS release, not Java 17. Application compatibility and the vendor support calendar still determine the right runtime; our guide to choosing a Java version explains the tradeoffs.

9) Build and Upload the JAR

Run exit to return to the same local terminal. Save this dependency-free application as Hello.java on your computer; it uses the JDK's HttpServer API.

import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;

public final class Hello {
    public static void main(String[] args) throws IOException {
        int port = args.length == 0 ? 8080 : Integer.parseInt(args[0]);
        HttpServer server = HttpServer.create(
                new InetSocketAddress("0.0.0.0", port), 0);
        server.createContext("/", exchange -> {
            byte[] body = "Hello from EC2\n".getBytes(StandardCharsets.UTF_8);
            exchange.getResponseHeaders().set(
                    "Content-Type", "text/plain; charset=utf-8");
            try {
                exchange.sendResponseHeaders(200, body.length);
                try (var output = exchange.getResponseBody()) {
                    output.write(body);
                }
            } finally {
                exchange.close();
            }
        });
        Runtime.getRuntime().addShutdownHook(new Thread(() -> server.stop(5)));
        server.start();
        System.out.println("Listening on " + port);
    }
}

Compile with local JDK 25 using javac, package with jar, and upload to the existing home directory:

javac --release 25 --add-modules jdk.httpserver -d out Hello.java
jar --create --file app.jar --main-class Hello -C out .
scp -i "$KEY" app.jar "ec2-user@$EC2_HOST:/home/ec2-user/app.jar"
ssh -i "$KEY" "ec2-user@$EC2_HOST"

10) Run the Application With systemd

Back on the instance, create a non-login service user and install a root-owned JAR:

sudo useradd --system --no-create-home --shell /sbin/nologin webapp
sudo mkdir /opt/webapp
sudo chmod 755 /opt/webapp
sudo cp /home/ec2-user/app.jar /opt/webapp/app.jar
sudo chmod 644 /opt/webapp/app.jar
sudo tee /etc/systemd/system/webapp.service <<'EOF'
[Unit]
Description=EC2 Java tutorial
After=network.target

[Service]
User=webapp
WorkingDirectory=/opt/webapp
ExecStart=/usr/bin/java --add-modules jdk.httpserver -Xmx256m -jar /opt/webapp/app.jar
Restart=on-failure
RestartSec=5
NoNewPrivileges=true
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
EOF
sudo systemctl daemon-reload
sudo systemctl enable --now webapp.service
sudo systemctl status webapp.service

The systemd service configuration restarts failed processes, subject to restart limits; enabling the service starts it on subsequent boots. The -Xmx256m option limits the Java heap, not total process memory.

11) Configure the Traffic Path

The application listens on port 8080, and the security group already permits your IP on that port. No port-80 redirect is needed. A security-group rule doesn't configure the operating-system firewall or start a listener; if you add a host firewall, configure it separately.

12) Verify, Inspect Logs, and Update

On the instance:

curl --fail http://127.0.0.1:8080/
sudo journalctl -u webapp.service -n 50 --no-pager

From your computer, open http://PUBLIC_IPV4:8080/. You should receive Hello from EC2. If local access works but remote access fails, check the public IP, routing, security-group source address, and host firewall.

For an update, upload the replacement JAR, stop the service, retain the previous artifact, replace the installed JAR, and restart the service. Verify the response and logs before accepting the deployment. Test reboot recovery before relying on it.

Using Elastic Beanstalk

Elastic Beanstalk manages deployment resources and configuration around your application; it doesn't remove operational responsibility. For an executable JAR, select a supported Java SE platform—not a Tomcat platform intended for servlet-container deployments.

  1. Create a Procfile alongside app.jar containing the command below.
  2. Create a ZIP source bundle with both files at its root, without an enclosing directory, following the source-bundle requirements.
  3. Create an application and web-server environment in the Beanstalk console. Select an AL2023 Java SE branch with Corretto 25 from the supported platforms, configure the required service role and instance profile, and upload the bundle.
  4. Review networking, environment capacity, health, and costs before creating it; then test the environment URL.
web: java --add-modules jdk.httpserver -Xmx256m -jar app.jar 5000

The Procfile specifies the application process. Here, the argument changes our sample's listening port to 5000, matching Beanstalk's default Java SE proxy destination.

Elastic Beanstalk has no separate service charge; underlying resources incur charges. A load-balanced environment can provision load balancing and Auto Scaling resources, while a single-instance environment has a different resource footprint.

Problems With Beanstalk?

A failed deployment may involve application startup, proxy routing, health checks, IAM permissions, or environment configuration. Inspect deployment events and application, proxy, and platform logs before making changes. Keep configuration in version control rather than relying on undocumented console edits.

Beanstalk is useful when its platform conventions fit your application. Direct EC2 management gives you more explicit control but leaves more setup to you; you can still automate it with infrastructure definitions and deployment pipelines.

Advertisement

Production Checklist

For a public service, use this as a starting architecture rather than exposing the tutorial instance:

Region / VPC
Client --HTTPS:443--> ALB in public subnets across AZ A and AZ B
                         |
                         | TCP:8080, instance SG source = ALB SG
                         +-- AZ A / private subnet --> EC2 --> Java
                         +-- AZ B / private subnet --> EC2 --> Java
  • Configure TLS, application authentication, least-privilege IAM, and secrets outside source code. See our Java web authentication guide.
  • Use an Auto Scaling group with a load balancer, multiple AZs, and explicitly enabled load-balancer health checks for instance replacement. Keep sessions and durable data outside replaceable instances.
  • Maintain OS and runtime updates, tested backups, centralized logs, application metrics, and alarms. Verify private-subnet outbound connectivity for administration and updates.
  • Automate deployments, retain rollback artifacts, and test instance replacement—not just process restarts.
  • After learning, terminate the instance and remove unneeded retained volumes, snapshots, addresses, and Beanstalk environments. Review billing afterward.

FAQ

How do I deploy a Java JAR to EC2 and keep it running after reboot?

Install a compatible Java runtime, upload the executable JAR, and configure a systemd service to run it as a non-root user. Enable the service for boot, configure a restart policy, and verify both application health and reboot recovery.

Which Java version should I use on EC2?

As of October 17, 2026, Java 25 is the latest LTS release. Choose a runtime supported by your application and vendor; this tutorial uses Amazon Corretto 25 on Amazon Linux 2023.

Can I use an EC2 instance for free?

Possibly, depending on your account creation date, Free Tier plan, credits, and eligible resources. Don't assume a particular instance is free, and check associated storage, public IPv4, and network charges before launching.

Is Elastic Beanstalk free?

Elastic Beanstalk has no separate service charge, but you pay for the underlying AWS resources. Instance count, storage, load balancing, networking, and monitoring affect the total.

Are Spot Instances always available?

No. Spot availability depends on spare EC2 capacity, and AWS can interrupt running Spot Instances. Use interruption-tolerant workloads with checkpointing and safe retries.

Further Reading

Advertisement

Written by Sam Erickson

Pen name of a software engineer with 20+ years in the industry, from Fortune 500 companies to startups. Newer articles are researched and drafted with AI tools I direct and fact-checked against their sources. Author of Mastering the Tech Interview. More about me

Advertisement
Amazon EC2 Tutorial: Instance Types, Pricing, and Java | StackChief