Skip to main content

OCI Compute Instances & OCPUs

Calculating read time…

Imagine you want to run your own computer program on the internet — like a website, an AI chatbot, or a game server. But you don't want to buy a big, expensive physical machine. 

That's exactly where OCI Compute Instances save the day! You borrow a super-powerful computer from Oracle's cloud, use it, and only pay for the time you use it. Simple as that! ☁️

💡 Think of it like: Renting a bicycle instead of buying one. You ride it, return it, and only pay for the hours you used it! 🚲




What is a Compute Instance?

A Compute Instance is a virtual computer that lives inside Oracle's giant data center. You can't touch it physically — but you can control it completely over the internet!

It comes with everything a real computer has:

  • Brain (CPU/OCPUs) = Does the thinking and calculations 🧠
  • Short-term memory (RAM) = Remembers what it's currently working on 💾
  • Storage (Hard Disk) = Saves your files permanently 💿
  • Network = Talks to the internet and other computers 🌐

💡 Real-life analogy: Think of Oracle's cloud like a giant hotel. Each Compute Instance is one hotel room. You book the room, use it, and check out when done. Oracle manages the building — you just enjoy your room! 🏨

Why Are Compute Instances So Important?

Almost everything on the internet runs on cloud compute instances. Here's why they matter so much:

  • No need to buy hardware → Start with just a few clicks and zero investment 💸
  • Pay only for what you use → Run it for 2 hours? Pay for just 2 hours! ⏱️
  • Scale instantly → Need more power? Upgrade in minutes, not weeks 📈
  • Run AI models → Train and serve ML models without buying expensive GPUs 🤖
  • Host globally → Put your app close to users in India, USA, Japan — everywhere! 🌍

🎯 Example: Your school project website suddenly gets 10,000 visitors. Instead of panicking, you just increase your Compute Instance size — done in 2 minutes!

What is an OCPU? 🧠

When you rent a Compute Instance, Oracle measures its computing power in OCPUs.

OCPU = Oracle Compute Unit

This is Oracle's special way of saying "how much brain power does your instance have?" But what exactly is 1 OCPU?

💡 Think of it like a pizza! 🍕

  • Imagine a full pizza = 1 physical CPU chip inside Oracle's server
  • That pizza is cut into slices — each slice = 1 core (one worker)
  • 1 OCPU = 1 full pizza slice (1 physical core)
  • But each slice can work on 2 things at the same time (called hyper-threading)
  • So 1 OCPU = 2 vCPUs (2 virtual CPU threads doing work together)

The most important formula to remember:

1 OCPU  =  1 Physical Core  =  2 vCPUs (virtual CPU threads)

So if you have 4 OCPUs → you actually get 8 vCPUs working for you at the same time! Pretty powerful, right? 💪

OCPU vs vCPU — What's the Difference?

Other cloud providers like AWS and Azure use vCPUs instead of OCPUs. This confuses beginners when comparing prices. Here's the simple breakdown:

┌──────────────────┬─────────────────────┬──────────────────────┐
│   What you get   │  1 OCPU (Oracle)    │  1 vCPU (AWS/Azure)  │
├──────────────────┼─────────────────────┼──────────────────────┤
│  Physical Cores  │        1            │        0.5           │
│  Working Threads │        2            │        1             │
│  Power Level     │    Full Core        │    Half Core         │
└──────────────────┴─────────────────────┴──────────────────────┘

Bottom line: 1 OCPU ≈ 2 vCPUs on AWS. Oracle gives you more power per unit! Always check this when comparing cloud prices. 🎯

Types of Compute Instances in OCI

OCI offers different Shapes — think of shapes like different sizes of hotel rooms. Small room, large suite, or a luxury penthouse — each has a different price and purpose!

Shape 1: Standard (General Purpose) — Most Common

Great for websites, APIs, learning projects, and everyday apps.

  • VM.Standard.A1.Flex → ARM-based. The cheapest! Also the Always Free option 🎁
  • VM.Standard.E5.Flex → AMD EPYC. Best price-to-performance⚡
  • VM.Standard3.Flex → Intel. Widely compatible with all software

Shape 2: GPU — For AI & Deep Learning

Massive computing power for training and running AI models.

  • VM.GPU.A10.1 → NVIDIA A10. Great for AI inference (serving predictions)
  • VM.GPU.L40S.1 → NVIDIA L40S. The sweet spot for AI.
  • BM.GPU.H100.8 → 8× NVIDIA H100. The absolute monster for training huge AI models

Shape 3: Always Free ← 🎉 FREE Forever!

Yes, Oracle gives you a real cloud server completely free, forever!

  • VM.Standard.A1.Flex → Up to 4 OCPUs + 24 GB RAM — FREE!
  • No credit card charges as long as you stay within free limits
  • Perfect for learning, small projects, and first-time experiments

💡 Beginner Tip: Start with the Always Free tier! You get 4 OCPUs and 24 GB RAM at zero cost. That's more than enough to host a website or run a small AI model. No need to spend money while learning! 🎓

How to Choose the Right OCPU Count?

Choosing OCPUs is like choosing the right engine size for a car. Too small = slow and sluggish. Too big = wasting money on power you don't need!

What Are You Building?                    OCPUs    RAM
─────────────────────────────────────────────────────────
📖  Learning / Personal experiments        1        6 GB
🌐  Small website or blog                  1        6 GB
🛒  Small shop (1,000 visitors/day)        2       12 GB
🏢  Medium app (10,000 users/day)          4       32 GB
🤖  AI model serving (inference)           8       64 GB
📊  Big data processing jobs              16      256 GB
🎮  Game server (50 players)               4       16 GB

✅ Pro tip: Always start small! Watch your CPU usage. If it stays above 80%, scale up. If it stays below 20%, scale down. This is called right-sizing — and it saves a lot of money! 💰

Step-by-Step: Create Your First Compute Instance

Let's create your first cloud server together! Follow each step carefully. 👇

Step 1: Create a Free OCI Account

  • Go to cloud.oracle.com and click "Start for free"
  • Enter your name, email, and phone number
  • Add a credit card (don't worry — Always Free won't charge you!)
  • Verify your email and phone OTP
  • ✅ Your account is ready!

Step 2: Open the Compute Section

  • Log in at cloud.oracle.com
  • Click the ☰ menu (top left corner)
  • Navigate to: Compute → Instances
  • Click the blue "Create Instance" button

Step 3: Name Your Instance & Pick a Shape

  • Give it a name like my-first-cloud-server
  • Click "Change Shape"
  • Select VM.Standard.A1.Flex (ARM — this is Always Free!)
  • Set OCPUs = 2 and Memory = 12 GB

Step 4: Choose Your Operating System

  • Click "Change Image"
  • Choose Ubuntu 24.04 — the easiest for beginners!

Step 5: Download Your SSH Key (Very Important!)

  • Under "Add SSH Keys", select "Generate a key pair for me"
  • Click "Save Private Key" — a .key file downloads to your computer
  • ⚠️ Keep this file very safe! It's like the key to your hotel room. Lose it = can't get in!

Step 6: Hit Create and Wait!

  • Scroll down and click the big "Create" button
  • Wait 1–3 minutes. Status will change: Provisioning → Running ✅
  • Note down the Public IP address shown on screen — you'll need it next!


Connect to Your Instance Using SSH

Now let's actually log in to your cloud server. It's like calling your hotel room through a special secure phone line!

💡 What is SSH? SSH (Secure Shell) is a way to connect your laptop to your server through the internet, through a secret encrypted tunnel. Nobody can eavesdrop on what you're doing! 🔐

📌 What the command below does: It opens a secure connection from your laptop to your OCI server using your downloaded key file. Once connected, you'll see your server's terminal — you're now controlling a computer that lives in Oracle's data center! 🖥️

# On Mac or Linux — open Terminal and run:
# Replace YOUR_KEY.key with your downloaded key file name
# Replace YOUR_IP with the Public IP of your OCI instance

ssh -i ~/Downloads/YOUR_KEY.key ubuntu@YOUR_IP

# Real example:
ssh -i ~/Downloads/ssh-key-2026.key ubuntu@152.70.45.100

When it asks "Are you sure you want to continue connecting?" — type yes and press Enter.

You'll see a welcome message from Ubuntu — that means you're inside your cloud server! 🎊

Install OCI CLI — Your Cloud Remote Control

The OCI CLI (Command Line Interface) lets you control your entire Oracle Cloud from your terminal — no clicking buttons on a website needed!

📌 What the command below does: It downloads and installs the official OCI CLI tool on your computer. After this, you can manage your entire cloud — create, delete, resize instances — all by typing commands. Think of it as installing a super-powered remote control! 🕹️

# For Mac / Linux — paste this into your Terminal:
bash -c "$(curl -L https://raw.githubusercontent.com/oracle/oci-cli/master/scripts/install/install.sh)"

Now link it to your Oracle Cloud account:

📌 What the command below does: It connects the OCI CLI to your Oracle Cloud account. Like logging into an app for the first time — you provide your account details once and it remembers them forever! 🔑

oci setup config

# It asks you these questions — answer each one:
# Config location    → press Enter (keep the default path)
# User OCID          → find in OCI Console → top-right profile icon
# Tenancy OCID       → OCI Console → Administration → Tenancy Details
# Region             → type: ap-mumbai-1  (or your closest region)
# Generate RSA keys? → type Y and press Enter

List Your Instances Using CLI

📌 What the command below does: It prints a table showing all your Compute Instances — their names, whether they're Running or Stopped, and which shape they are. Like asking the hotel front desk: "show me all my bookings!" 📋

# Replace YOUR_COMPARTMENT_ID with your compartment OCID
oci compute instance list \
  --compartment-id YOUR_COMPARTMENT_ID \
  --output table

Output:

+---------------------+-----------------+-------------+---------------------------+
| display-name        | lifecycle-state | region      | shape                     |
+---------------------+-----------------+-------------+---------------------------+
| my-first-server     | RUNNING         | ap-mumbai-1 | VM.Standard.A1.Flex       |
| dev-testing-box     | STOPPED         | ap-mumbai-1 | VM.Standard.E5.Flex       |
+---------------------+-----------------+-------------+---------------------------+

Your instances listed in a clean table! 🎯

Change OCPU Count Using CLI

📌 What the three commands below do: They first stop your instance (switching it off), then upgrade its OCPUs and RAM (giving it a bigger engine), then start it back up. Your server comes back stronger — with more power! 💪

# Step 1: Stop the instance first (like switching off a computer before upgrading)
oci compute instance action \
  --instance-id YOUR_INSTANCE_OCID \
  --action STOP

# Step 2: Upgrade — change from 2 OCPUs/12 GB to 4 OCPUs/24 GB
oci compute instance update \
  --instance-id YOUR_INSTANCE_OCID \
  --shape-config '{"ocpus": 4, "memoryInGBs": 24}'

# Step 3: Start it back up!
oci compute instance action \
  --instance-id YOUR_INSTANCE_OCID \
  --action START

That's it! Your server now has 4 OCPUs and 24 GB RAM. 🚀

Control OCI Compute with Python SDK 🐍

Want to manage your cloud using Python code? That's what the OCI Python SDK is for! Perfect for automating things and building smarter apps.

Install the Python SDK

📌 What the command below does: It installs Oracle's official Python library on your computer. After this, your Python scripts can talk directly to Oracle Cloud — creating servers, checking them, deleting them — all with code! 🐍

pip install oci

List All Instances with Python

📌 What the code below does: This Python script connects to your Oracle Cloud account and fetches a list of all your Compute Instances. For each one, it prints the name, whether it's Running or Stopped, the shape name, and the number of OCPUs and GB of RAM. It's like getting your hotel booking list — but in Python! 📋

import oci

# Load your OCI account details from the config file set up earlier
config = oci.config.from_file()

# Create a compute client — our "connection" to Oracle Cloud
compute_client = oci.core.ComputeClient(config)

# Your compartment OCID — find in OCI Console → Identity → Compartments
compartment_id = "ocid1.compartment.oc1..xxxxxxxxxxxxxx"

# Fetch all instances in this compartment
instances = compute_client.list_instances(compartment_id=compartment_id)

# Print details for each instance
print("=" * 50)
print("  MY OCI COMPUTE INSTANCES")
print("=" * 50)

for instance in instances.data:
    shape_config = instance.shape_config
    print(f"  Name    : {instance.display_name}")
    print(f"  Status  : {instance.lifecycle_state}")
    print(f"  Shape   : {instance.shape}")
    print(f"  OCPUs   : {shape_config.ocpus}")
    print(f"  RAM(GB) : {shape_config.memory_in_gbs}")
    print("-" * 50)

Output:

==================================================
  MY OCI COMPUTE INSTANCES
==================================================
  Name    : my-first-server
  Status  : RUNNING
  Shape   : VM.Standard.A1.Flex
  OCPUs   : 2
  RAM(GB) : 12.0
--------------------------------------------------
  Name    : dev-testing-box
  Status  : STOPPED
  Shape   : VM.Standard.E5.Flex
  OCPUs   : 4
  RAM(GB) : 32.0
--------------------------------------------------

All your instances printed beautifully — just with Python! 🎉

Create a New Instance with Python

📌 What the code below does: This script automatically creates a brand new Compute Instance entirely from Python. You tell it the size (OCPUs, RAM), which OS to install, and which network to use — and Oracle does the rest. It's like booking a hotel room through a website — except the website is your Python script! 🏨

import oci

config = oci.config.from_file()
compute_client = oci.core.ComputeClient(config)

# --- Fill in your own values here ---
COMPARTMENT_ID      = "ocid1.compartment.oc1..xxxxxxxxx"
AVAILABILITY_DOMAIN = "AD-1"
SUBNET_ID           = "ocid1.subnet.oc1..xxxxxxxxxxx"
IMAGE_ID            = "ocid1.image.oc1..xxxxxxxxxxx"   # Ubuntu 24.04 ARM image OCID
# ------------------------------------

# Describe what kind of instance we want
instance_details = oci.core.models.LaunchInstanceDetails(
    compartment_id      = COMPARTMENT_ID,
    availability_domain = AVAILABILITY_DOMAIN,
    display_name        = "python-created-server",

    # Shape = the type of virtual machine. A1.Flex is ARM and Always Free eligible!
    shape = "VM.Standard.A1.Flex",

    # How many OCPUs and how much RAM?
    shape_config = oci.core.models.LaunchInstanceShapeConfigDetails(
        ocpus         = 2,    # 2 OCPUs = 4 vCPUs of processing power
        memory_in_gbs = 12    # 12 GB of RAM
    ),

    # Which operating system image to install
    source_details = oci.core.models.InstanceSourceViaImageDetails(
        source_type = "image",
        image_id    = IMAGE_ID
    ),

    # Network settings — give it a public IP so we can reach it from the internet
    create_vnic_details = oci.core.models.CreateVnicDetails(
        subnet_id        = SUBNET_ID,
        assign_public_ip = True
    )
)

# Launch the instance!
response = compute_client.launch_instance(instance_details)

print(f"✅ Instance created!")
print(f"   Name   : {response.data.display_name}")
print(f"   Status : {response.data.lifecycle_state}")
print(f"   Shape  : {response.data.shape}")
print(f"   ID     : {response.data.id}")

Output:

✅ Instance created!
   Name   : python-created-server
   Status : PROVISIONING
   Shape  : VM.Standard.A1.Flex
   ID     : ocid1.instance.oc1.ap-mumbai-1.xxxxx

Your brand new server was created by your Python script! How cool is that? 😎

Monitor CPU & OCPU Usage with Python

After your instance is running, you want to keep an eye on how hard it's working. If the CPU is always at 90%+, your server is overwhelmed — time to add more OCPUs!

📌 What the code below does: It checks how busy your instance's OCPUs have been over the last hour. It prints the CPU usage percentage for every minute — like a speedometer for your server. High % = your server is working very hard. Low % = it's just chilling! 🚗

import oci
from datetime import datetime, timedelta, timezone

config = oci.config.from_file()
monitoring_client = oci.monitoring.MonitoringClient(config)

COMPARTMENT_ID = "ocid1.compartment.oc1..xxxxxxxxx"
INSTANCE_OCID  = "ocid1.instance.oc1..xxxxxxxxx"

# Look at the last 1 hour of data
end_time   = datetime.now(timezone.utc)
start_time = end_time - timedelta(hours=1)

# MQL query = asking OCI: "give me average CPU % for my instance, per minute"
mql_query = (
    f'CpuUtilization[1m]'
    f'{{resourceId = "{INSTANCE_OCID}"}}'
    f'.mean()'
)

response = monitoring_client.summarize_metrics_data(
    compartment_id = COMPARTMENT_ID,
    summarize_metrics_data_details = oci.monitoring.models.SummarizeMetricsDataDetails(
        namespace  = "oci_computeagent",
        query      = mql_query,
        start_time = start_time.isoformat(),
        end_time   = end_time.isoformat()
    )
)

# Print the last 5 readings with a simple bar chart
print("⚡ CPU Usage — Last 5 Minutes:")
print("-" * 45)

for metric_data in response.data:
    for datapoint in metric_data.aggregated_datapoints[-5:]:
        time_str = datapoint.timestamp.strftime("%H:%M")
        usage    = round(datapoint.value, 1)
        bar      = "█" * int(usage / 5)
        print(f"  {time_str}  {bar:<20 code="" usage="">

Output:

⚡ CPU Usage — Last 5 Minutes:
---------------------------------------------
  14:00  ████                   23.5%
  14:01  ██                     12.1%
  14:02  ██████████             52.3%
  14:03  ████████████████       82.7%
  14:04  ███                    17.4%

At 14:03, the CPU hit 82.7% — if that keeps happening for a long time, it's time to add more OCPUs! 📊

Real Example: Run an AI App on OCI ☁️🤖

Let's bring it all together with something really exciting — running an actual AI model on your OCI Compute Instance. This is exactly what startups and developers do !

📌 What the code below does: It creates a tiny web API that anyone in the world can send text to. The API uses an AI model from Hugging Face to read the text and decide if it sounds positive 😊 or negative 😠. Your OCI instance's OCPUs do all the AI thinking — automatically! Send "I love cloud!" → get back "POSITIVE, 99.8% confident!" 🤖

# First, install these on your OCI instance terminal:
# pip install fastapi uvicorn transformers torch

from fastapi import FastAPI
from pydantic import BaseModel
from transformers import pipeline

# Create our web application
app = FastAPI(title="My AI API — Powered by OCI ☁️")

# Load a pre-trained AI model from Hugging Face
# It runs on your OCI instance's OCPUs — no special GPU needed for this one!
print("⏳ Loading AI model... (takes ~30 seconds the first time)")
sentiment_model = pipeline(
    "sentiment-analysis",
    model = "distilbert-base-uncased-finetuned-sst-2-english"
)
print("✅ AI model is ready!")

# This defines what a user's request looks like — just a piece of text
class TextRequest(BaseModel):
    text: str

# The API endpoint — the URL path people send text to
@app.post("/analyze")
def analyze_sentiment(request: TextRequest):
    # The AI model reads the text and gives a result
    result = sentiment_model(request.text)[0]

    return {
        "your_text"  : request.text,
        "sentiment"  : result["label"],                     # POSITIVE or NEGATIVE
        "confidence" : round(result["score"] * 100, 2),    # How sure the AI is (in %)
        "server"     : "OCI Compute — VM.Standard.A1.Flex ☁️"
    }

# To start the API on your OCI server, run this command in terminal:
# uvicorn app:app --host 0.0.0.0 --port 8000

Now test it from anywhere in the world! 🌍

# Replace YOUR_OCI_IP with your instance's Public IP
curl -X POST "http://YOUR_OCI_IP:8000/analyze" \
     -H "Content-Type: application/json" \
     -d '{"text": "OCI Compute Instances are absolutely amazing!"}'

Output:

{
  "your_text"  : "OCI Compute Instances are absolutely amazing!",
  "sentiment"  : "POSITIVE",
  "confidence" : 99.87,
  "server"     : "OCI Compute — VM.Standard.A1.Flex ☁️"
}

Your AI API is live on the internet — powered entirely by your OCI instance! 🌍🎉

Do's and Don'ts ✅❌

✅ DO — Good Habits for Beginners
  • Start with the Always Free tier to learn without spending money 🎓
  • Stop your instance when you're not using it — saves cost!
  • Take Boot Volume Backups before making big changes
  • Monitor CPU usage and right-size your instance regularly
  • Use SSH keys — always. Never password-based SSH
❌ DON'T — Avoid These Mistakes
  • Don't leave instances running 24/7 if you only use them sometimes — you'll be charged!
  • Don't pick a huge OCPU count for a tiny project — that's just wasted money
  • Don't lose your SSH private key file — you won't be able to log in!
  • Don't skip OS updates — unpatched servers get hacked very quickly
  • Don't open all firewall ports — only open what you actually need
💡 Important Tips to Remember
  • 1 OCPU = 2 vCPUs — remember this when comparing Oracle vs AWS pricing!
  • Always Free = 4 OCPUs + 24 GB RAM — use it for all your learning!
  • CPU above 80% consistently? → Scale up your OCPU count
  • CPU below 20% always? → Scale down and save money
  • ARM shapes (A1.Flex) are the cheapest and most efficient option

Quick Summary 📝

What we learned:

  • Compute Instance → A virtual computer you rent from Oracle's cloud
  • OCPU → Oracle's unit for CPU power. 1 OCPU = 1 physical core = 2 vCPUs
  • Shapes → Different instance types — Standard, GPU, and Always Free
  • Always Free Tier → 4 OCPUs + 24 GB RAM, completely free, forever
  • SSH → How you securely log into and control your instance
  • OCI CLI → Manage your cloud from terminal — list, resize, start, stop
  • Python SDK → Create and manage instances using Python code
  • Monitoring → Check CPU % to decide when to add or remove OCPUs
  • AI on OCI → Run Hugging Face models on your instance with FastAPI
  • Security → Firewall + SSH keys + OS updates = a safe server 🔐

Happy cloud learning! ☁️✨

Comments