Cloud Deployment for Machine Learning Beginners: Hosting Python Models on AWS, Google Cloud and Microsoft Azure

Imagine a student who has built a historical house-price Random Forest in Python, exposed it through FastAPI, and packaged its inference code in a Docker image. The program runs on their laptop, but classmates in other countries cannot open a local development address. Can one trusted model be hosted on AWS, Google Cloud, or Microsoft Azure without learning three entirely different programming languages or accidentally creating a large cloud bill? This cloud deployment for machine learning beginners guide answers that question with one application and three alternative hosting routes.

The teaching project builds on Topic 96: Docker, Topic 93: FastAPI and Topic 94: MLOps. The focus here is identity, image registries, provider-managed hosting, safe networking, billing and cleanup—not rewriting the previous model-development tutorials.

Verification and limits (25 November 2026): The companion Python project was created; thirteen automated tests passed using explicitly fictional synthetic model fixtures, and Python syntax compilation passed. Authentic Ames Housing training, Docker image building, remote registry publication and AWS/Google Cloud/Azure service deployment have not been completed. No billable resources, cloud accounts or public endpoint were created. All dollar predictions require actual model execution after obtaining the source dataset. Cloud instructions are educational procedures, not evidence of a running service.

What is cloud computing?

Cloud computing makes compute, networking, storage and managed software available over a network. Providers operate physical infrastructure and expose services through managed platforms. A student can run code remotely without buying a physical server, but must still manage application logic, privacy, resource access and bills.

Cloud hosting does not make model predictions more accurate. It changes where and how software runs. The same biased or poorly evaluated regression model remains scientifically weak if it responds over HTTPS. Train and evaluate before publishing any endpoint.

Local execution versus cloud hosting

Localhost refers to the execution environment making or receiving a request. A development service at 127.0.0.1:8000 is normally not a public URL. A managed container service can assign a configured HTTPS endpoint and accept requests according to identity and ingress policies. A private endpoint may require authenticated service-to-service requests.

Local training avoids live hosting charges; managed cloud hosting can improve remote access and simplify selected operations but introduces billing, network exposure and startup delays. Students without an authorized paid account can complete the offline parts, cost arithmetic and deployment design before using cloud services.

IaaS, PaaS, SaaS, managed containers and serverless

Infrastructure as a Service provides lower-level configurable infrastructure such as virtual machines. Platform as a Service manages more of the application runtime. Software as a Service provides complete applications to customers. Managed container services operate user-supplied images while handling selected infrastructure responsibilities. These service models overlap in practice.

Serverless refers to managed execution and often usage-related scaling; it never means that the service operates without physical servers. AWS ECS Express Mode, Google Cloud Run and Azure Container Apps each manage different infrastructure and must not be described as identical products.

Regions, capacity and deployment choices

Cloud regions are geographic groups of provider infrastructure. They influence network latency, pricing, residency and service availability. Choose a region only after checking that the intended container service and registry support it. An international educational audience should not assume any country is a universal default.

Cloud autoscaling adjusts capacity according to platform-specific rules. Cold starts can add latency while a new Python container begins loading its model. A higher minimum instance count may reduce startup delays but increase spending. Measure actual memory and response times before optimizing.

One FastAPI model, three cloud paths

The reusable architecture is: verified data → trained fitted Pipeline → trusted Joblib artifact → FastAPI → Docker image → authorized registry → managed container host → HTTPS API → authorized client. The core code and six-feature contract can remain stable as the provider-specific IAM and deployment configuration change.

The common application exposes GET /health, GET /ready, GET /model-info and POST /predict. An operational readiness check does not prove statistical accuracy; the model must be tested against actual held-out outcomes separately.

Conceptual deployment architecture linking one trusted FastAPI model with AWS, Google Cloud and Azure
Original conceptual diagram—not a live deployment screenshot.

The six required Ames Housing features

The historical dataset is OpenML 42165, commonly used with 1,460 housing records from Ames, Iowa, and SalePrice as target. The prediction inputs are GrLivArea, OverallQual, YearBuilt, TotalBsmtSF, GarageCars and FullBath. Area is measured in square feet; quality is an ordinal rating; the other values are construction year and counts. The model intentionally omits many real-estate factors and is unsuitable as a modern professional valuation service.

Feature names, ordering, types, units and fitted preprocessing must match between the offline model, Docker image and cloud inference. Sending square metres when the forest expects square feet is a serious error even if the API accepts a number.

FeatureInterpretationSample value
GrLivAreaAbove-ground square feet1500
OverallQualQuality rating6
YearBuiltOriginal construction year1995
TotalBsmtSFBasement square feet800
GarageCarsGarage capacity2
FullBathFull bathrooms2

Offline training, held-out testing and serialization

The downloadable training script retrieves actual OpenML 42165 when network access is available, checks the source columns, splits the records 80/20 with seed 97, fits median imputation and RandomForestRegressor, and compares it with a median-only baseline. It writes genuine MAE, R², sample counts, package version, feature schema and an artifact checksum when run successfully.

It saves the complete fitted Scikit-learn Pipeline instead of only the forest. The API should not recompute replacement medians from visitor requests or train a model during container startup. No real Ames performance statistics are claimed here because the authentic dataset was not retrieved.

Model artifact security and API validation

Joblib uses pickle-based persistence that may execute code when loading an untrusted artifact. Never deserialize public user submissions or unknown model downloads. The backend checks expected feature order, Scikit-learn compatibility and checksum before loading an independently trusted source. A checksum is not sufficient authentication if both model and hash can be replaced by an attacker.

Pydantic validates ranges, required names and nonfinite values. A JSON body can be syntactically correct while scientifically invalid, so input guardrails must not be treated as proof that the property resembles the training population. Unexpected or missing features receive an error rather than a fabricated value.

Cloud-ready Dockerfile and port behaviour

The source project uses a Python 3.12 slim base, installs FastAPI, Uvicorn, Pydantic, Pandas, NumPy, Scikit-learn and Joblib, copies application code and trusted model, selects a non-root process user and starts Uvicorn on 0.0.0.0. The startup command reads the configured PORT with fallback 8000. This is necessary for platforms such as Cloud Run that inject a port environment variable.

Before any cloud publish, execute a real local Docker build, confirm image contents and verify health, model readiness, version, valid prediction, rejected invalid request and no bundled secrets. Docker is unavailable in this authoring environment, so the image and commands remain unverified until execution elsewhere.

docker build -t historical-housing-api:local .
docker run --rm -p 127.0.0.1:8000:8000 historical-housing-api:local
# Test locally: http://127.0.0.1:8000/docs

What beginners must understand about cloud billing

How an idle service can still produce a bill

A cost estimate has to follow the infrastructure, not just the number of predictions. An AWS deployment can include a Fargate task, load balancer, networking components and log storage whose charging models differ. A Google Cloud Run service can have a minimum-instance policy or other service settings affecting idle consumption. Azure Container Apps can have replica, registry and diagnostic settings with their own billing treatment. No single hourly example represents all these systems.

When a student visits a dashboard and sees zero requests, that observation does not prove zero compute or supporting-resource charges. Estimate each component separately, then monitor the provider’s actual cost data after deployment. Keep a written record of start time, enabled services, selected region, resource sizes and the exact resources the experiment owns.

Understand pricing calculators before activation

An official pricing calculator is an estimate builder, not a guaranteed bill. Enter the relevant region, CPU, memory, expected active time, traffic assumptions and supporting components. A calculator that omits network egress, load-balancing resources, image storage or logs can understate the full bill. Some pricing depends on how many seconds or requests are billed, whereas other resources can charge over continuous elapsed time.

A practical classroom worksheet should record the assumptions, date of estimate and provider source. Use several scenarios such as five hours, one day and thirty days. Recheck the estimate whenever a resource configuration changes, because moving from one instance to multiple minimum instances can change expenses even when the application code stays identical.

Budget alerts, quotas and spending limits are different controls

A budget alert generally warns about spending. A quota limits a particular resource or operation, such as the number of instances, but is not a comprehensive financial cap. A provider-specific spend control, where available, may cover only particular services. Students should not assume setting a ten-dollar budget prevents an eleven-dollar bill.

For a controlled project, assign an account owner, set a clear maximum affordable amount, document when the demo will be stopped and establish a cleanup checklist. The safest decision when cost permissions are absent is to prepare and validate the project locally without creating cloud resources. This still meets the educational aim of understanding how the architecture works.

IAM roles, service accounts and managed identities

Cloud identity is not one global credential shared among AWS, Google Cloud and Azure. AWS IAM grants permissions through identities, roles and policies. Google Cloud uses principals, service accounts and IAM bindings. Azure uses Entra identities, managed identities and role assignments under Azure RBAC. A deployment credential may need permission to upload an image while the running application needs only enough access to serve its model.

The student should record which role creates resources, which role allows the container service to pull the image, and which identity invokes the endpoint. Avoid giving the running inference service broad permissions to modify billing, delete infrastructure or administer unrelated resources. Keep long-lived private keys out of source code and use supported workload identity mechanisms.

Understand public access and private API invocation

A public HTTPS endpoint can be called by internet clients according to its configured authentication and network rules. A private endpoint may require IAM invocation permission, a valid identity token or private network connectivity. A browser receiving HTTP 403 may be operating correctly if the resource is restricted; removing authentication simply to make the error disappear creates unnecessary exposure.

Students should distinguish network reachability, authentication and authorization. A request may reach the service but be rejected because the caller lacks permission. An authenticated caller may still be blocked by an ingress restriction. These protections are separate and should be tested deliberately before publishing any live link.

How to measure a cloud deployment after release

Verification must use the genuine provider-assigned endpoint, not an invented localhost address. Record the deployed image digest and model version, call /health to inspect basic server responsiveness, call /ready to confirm approved model loading, and request /model-info to confirm the feature schema and source. Next send a valid six-feature JSON payload and verify the returned number is finite and consistent with the trusted local model.

Deliberately omit a required feature, send an invalid quality rating and add an unexpected field to confirm validation errors. Inspect provider logs without recording unnecessary visitor data. Finally review CPU, memory, startup events and real billing to ensure the demo is not consuming more resources than intended.

Cold starts, concurrency and request timeouts

A managed service may initialize a new container when demand appears or instances scale up. This process can take longer than a warmed request, particularly when Python imports large libraries and deserializes a forest. Some platforms allow minimum instances, but this can increase cost. Running multiple workers may increase memory pressure because a model can be loaded into more than one process.

Choose conservative resource settings and measure actual behaviour. Do not promise subsecond predictions or instant cold starts without logs and repeatable measurements. A client should have a documented timeout and handle errors gracefully. For this historical education demo, latency optimization is less important than correct model loading, access control and predictable spending.

Cloud cleanup should be audited twice

When the exercise is finished, inspect all demonstration resources, not just the main application. Verify image registries, build outputs, any load balancer or network resources, logging destinations, service identities and supporting environments. Then delete only resources created specifically for the demo. Shared projects, resource groups, network components or registries may be used by other applications.

Afterward, reopen the service inventory and billing report. Confirm the application no longer runs and note any remaining retained storage or log charges. Some cost reporting is delayed, so a clean immediate dashboard does not prove that all usage has already appeared. A written cleanup record is part of the capstone evidence.

Privacy and responsible AI when students build online demos

A student-facing demo should not require collecting real addresses or identifiable household information. Historical model measurements are enough for an educational exercise. Avoid persisting payloads or logging values that could identify users. If a class switches to student grades or health information, it needs a different privacy and authorization review.

Predictive accuracy, fairness, privacy and security are separate responsibilities. An HTTPS service with strong IAM could still contain a biased or inaccurate model. Conversely, a statistically good model could reveal private inputs through careless logs. Good cloud engineering checks each risk independently and clearly explains the demo’s limited purpose.

A free tier, promotional credit, trial and pay-as-you-go subscription have different conditions. Some charges continue when requests stop, especially for supporting infrastructure, registry storage, networks, logging or minimum running capacity. A free allowance is not universal permission to run every configuration for no charge.

Set a tolerable spending budget, inspect provider pricing calculators and verify whether a budget alert merely notifies or can take a supported action. AWS Budgets, Google Cloud Billing Budgets and Azure Cost Management all require account-specific configuration. Do not assume that an alert is a hard cap.

Two verified but fictional cost exercises

For a fictional service component at $0.04 per hour running five hours, the component costs $0.20. At a fictional $0.06 per hour over thirty complete days, there are 720 hours and the component costs $43.20. These are arithmetic demonstrations, not the current price of AWS ECS, Cloud Run or Azure Container Apps.

Actual charges depend on region, CPU, memory, minimum instances, request volumes, supporting services, network transfer and logs. Use official calculators for a live quote and include a cleanup plan before authorizing any resource.

Conceptual steps for cloud spending guardrails, identity, endpoint verification and resource cleanup
Original cost-and-security workflow illustration.

AWS: ECS Express Mode, ECR and IAM

AWS App Runner closed to new customers on April 30, 2026. New learners should follow AWS’s current recommendation of Amazon ECS Express Mode. It builds on ECS and Fargate, managing some supporting infrastructure such as load balancing, networking and scaling. However, Fargate compute, load balancers, ECR, CloudWatch and network transfer may create costs.

A safe AWS sequence is: confirm IAM and billing authorization; select a supported region; configure a budget; obtain the trusted image; create/select an ECR repository; authenticate and push the image; review ECS task execution and infrastructure roles; configure port 8000, capacity and health; inspect expected supporting resources; and create the service only after approval. Never invent role ARNs or account IDs.

AWS: real verification and cleanup

After deployment, confirm the ECS service and actual HTTPS endpoint, call /health and /ready, inspect the correct model version, exercise one valid and one invalid prediction, and review CloudWatch and resource charges. A service showing ‘active’ does not prove the model is accurate or that the endpoint is accessible to permitted clients.

At the end, remove demo-owned ECS resources, inspect any remaining load balancer, networking, ECR and CloudWatch resources, remove unneeded demo roles and verify billing. Deleting one main resource may leave related resources behind. Shared infrastructure must not be deleted.

Google Cloud: Artifact Registry and Cloud Run

Google Cloud Run hosts containers as managed HTTP services. After confirming project billing, IAM permissions and regional availability, enable only required APIs, create an authorized Artifact Registry repository and push the verified image. Choose a service account with least privilege. Cloud Run injects PORT, so the image must listen correctly.

The deployment settings include memory/CPU, concurrency, scaling, ingress and authentication. A private demonstration may use a command template such as gcloud run deploy ml-housing-api --image IMAGE_URI --region REGION --port 8000 --no-allow-unauthenticated. IMAGE_URI and REGION are placeholders, not real identifiers.

Google Cloud: authenticated invocation and cleanup

A private Cloud Run service requires an appropriate invoker identity and valid request authentication. A public Streamlit frontend should not embed a permanent service-account key in browser JavaScript. Use authorized service-to-service identity, restrict ingress where required and verify actual HTTPS requests.

After the demonstration, remove the dedicated Cloud Run service and unused Artifact Registry images, build artifacts or dedicated identities, then inspect billing. Revisions, minimum instances, concurrency and logs can affect behaviour and costs. Cloud Run is not automatically free in every configuration.

Azure: Container Registry, managed identities and Container Apps

Azure Container Apps provides managed container execution with ingress, revisions, replicas and Azure ecosystem integrations. Start by confirming an authorized subscription and a resource group, then verify region and resource-provider support, quotas and Cost Management budgets. Use Azure Container Registry to hold the reviewed image and configure least-privilege access.

A managed identity can help access an image registry without embedding long-lived passwords, but its required role assignment must still be configured. Container Apps ingress can be internal or external under the environment’s networking rules. External ingress makes the application reachable through a configured public entrypoint and should be approved deliberately.

Azure: illustrative deployment and cleanup

After provisioning prerequisites, the relevant command pattern is az containerapp up --name ml-housing-api --resource-group RESOURCE_GROUP --environment ENVIRONMENT_NAME --image IMAGE_URI --ingress external --target-port 8000. It illustrates a public deployment, not a safe default for unapproved classroom use. The named group, environment, image and identity must genuinely exist.

Verify the actual endpoint, /ready, model information, prediction, HTTP errors, logs, scaling and charges. Clean up only dedicated demo apps, environments, images, registries, diagnostic workspaces and identity assignments. Never remove a shared resource group just to complete a lesson.

CriterionAWSGoogle CloudAzure
HostingECS Express ModeCloud RunContainer Apps
RegistryECRArtifact RegistryACR
AccessIAM rolesIAM/service accountsRBAC/managed identities
MonitoringCloudWatchCloud LoggingAzure Monitor
NetworkECS/VPC and ALBCloud Run ingressContainer Apps ingress
CostsFargate and supporting resourcesCompute/requests/storage/networkReplicas/storage/logging/network

Which provider should a beginner choose?

Select the provider for which authorized accounts, eligible trial resources, relevant regional support and an affordable cost estimate are available. AWS teaches ECS/Fargate infrastructure and IAM; Google Cloud teaches managed HTTP containers and authenticated invocation; Azure teaches Container Apps environments, registry and managed identity. There is no universally best choice for every student.

Students should begin with one provider, not three simultaneous deployments. Exploring documentation for all three and designing one test plan is useful even without a credit card or cloud subscription. The core project is intentionally runnable locally after authentic model training.

Cloud portability: what changes across providers?

The Docker image, six features, API methods, general response meaning and trusted Scikit-learn Pipeline can be portable if the target architecture and dependencies are compatible. But IAM policies, identity bindings, registry paths, network exposure, monitoring, autoscaling and billing vary significantly.

A successful image push is not a successful deployment; a successful service start is not a validated prediction; a successful model evaluation is not a secure public API. Verify each stage independently.

Security: private access, HTTPS and workload identities

Begin with least-privilege access and private or deliberately restricted endpoints. Keep credentials out of downloadable notebooks, source repositories, Dockerfiles and WordPress JavaScript. Use provider-supported identity-based authentication, secret managers and authorized certificate/HTTPS configurations. Protect image registries and serialized model provenance.

Public demos need request controls, acceptable-use policies, abuse monitoring, resource quotas and an agreed budget. A non-root user reduces some risks but does not guarantee safety. Validate and restrict inputs, review dependencies and avoid recording sensitive visitor information unnecessarily.

Connecting Streamlit and Notes for SHS

A separate Streamlit application can call a deployed FastAPI service using secure server-side HTTP, proper authentication and timeouts. A private backend is not automatically callable from arbitrary public browsers. For Notes for SHS, a verified educational demo link is usually simpler than an untested iframe or custom-domain change.

Do not add an invented cloud service URL to the article. An application URL should be published only after opening it, confirming model version, testing valid/invalid requests and checking mobile readability.

Monitoring, cold starts, updates and rollback

Track service availability, errors, response latency, memory, CPU, instance counts and container startup behaviour. Independently monitor feature distributions, prediction drift and actual model error when trustworthy labels are available. A healthy cloud API can still make poor predictions.

Before updating, evaluate the new model, record its artifact hash, build an approved image and test compatibility. Record immutable image references, deploy under controlled approval and retain a rollback path. A failed new version should be restored from a previously verified compatible image, followed by real endpoint checks.

Ten-task student capstone

Tasks 1–3: identify one provider; verify OpenML 42165 source and six features; evaluate an offline model against a baseline with real held-out outcomes. Tasks 4–6: save the trusted Pipeline, build/test the Docker image, and prepare an account-specific cost, permissions and region plan.

Tasks 7–10: with authorization, create an image registry, deploy a service, verify HTTPS and four endpoints, document scaling and monitoring, and safely remove demonstration-owned resources. Without billing approval, submit the deployment design and simulated checklist, explicitly marking each remote operation unexecuted.

Thirty student practice questions with answers

Question 1: Define cloud computing.

Managed network-delivered computing resources.

Question 2: Define cloud deployment.

Hosting an application on authorized remote infrastructure.

Question 3: Does cloud hosting improve model accuracy?

No.

Question 4: What is IaaS?

Infrastructure as a Service.

Question 5: What is serverless?

Provider-managed execution; servers still exist.

Question 6: Why use Docker?

Package compatible code and dependencies.

Question 7: Name the AWS hosting service.

ECS Express Mode.

Question 8: Why not recommend App Runner to new users?

Closed to new customers in April 2026.

Question 9: Name Google’s service.

Cloud Run.

Question 10: Name Azure’s service.

Container Apps.

Question 11: What is a cloud region?

A geographic provider resource location.

Question 12: What is IAM?

Identity and Access Management.

Question 13: What is a service account?

A workload identity.

Question 14: Does managed identity grant all roles automatically?

No.

Question 15: What is a registry?

Image storage and distribution service.

Question 16: Does image push create a public API?

No.

Question 17: Why must feature order stay fixed?

To avoid incorrect inference mapping.

Question 18: What is SalePrice?

The historical target.

Question 19: Why save a fitted Pipeline?

Preserve learned preprocessing and forest.

Question 20: Why not load unknown Joblib artifacts?

Deserialization can execute code.

Question 21: What is /ready?

Model readiness check.

Question 22: What does 422 indicate?

Request validation error.

Question 23: Why must Cloud Run respect PORT?

It defines the ingress container listening port.

Question 24: Is a budget alert always a hard cap?

No.

Question 25: Calculate 5×$0.04.

$0.20.

Question 26: Calculate 720×$0.06.

$43.20.

Question 27: Define cold start.

New instance initialization delay.

Question 28: Why HTTPS?

Encrypt data in transit.

Question 29: What is rollback?

Restore a previously approved version.

Question 30: How do you prove deployment worked?

Inspect a real endpoint, authentication, version, predictions, error handling, logs and billing.

Four-week learning roadmap

Week 1: study cloud computing, regions, identity, serverless and cost controls. Week 2: run authentic model training, evaluation and local Docker tests. Week 3: compare AWS ECS Express Mode, Google Cloud Run and Azure Container Apps; design secure deployment for one. Week 4: where authorized, deploy and verify a short demonstration, inspect cost and logs, then clean up; otherwise submit the complete unexecuted deployment plan.

Frequently asked questions

Can I learn without paying? Yes, the code, comparisons and deployment plan can be completed locally, though real cloud execution may require billing authorization. Which platform is best? Choose according to access, cost and learning goals. Can Cloud Run be private? Yes, using configured invocation permissions. Can Azure be internal? Container Apps supports internal ingress under its networking model. Is ECS Express Mode universally free? No. Are the Ames numbers verified here? No, genuine data retrieval was unavailable. Is any cloud endpoint live? None was created.

Primary documentation and internal lessons

For current details see AWS ECS Express Mode, AWS App Runner update, Google Cloud Run, Azure Container Apps, Docker and Scikit-learn persistence. Prior lessons: Topic 96, Topic 95, Topic 94, and Topic 92.

Conclusion: verify model, infrastructure, security and cost separately

Cloud deployment is not simply moving a notebook online. A properly prepared model needs consistent preprocessing, a trusted serialized artifact, a tested API, an approved container image and a carefully configured service. AWS, Google Cloud and Azure offer different supported paths to that goal, but all require identity, networking, monitoring and billing decisions.

The companion project lets students practise the Python side without fabricating a real trained model or spending money. Choose one provider, require approval before provisioning, validate the real HTTPS service and clean up carefully. Responsible engineering documents what was actually executed, what remains unverified and why the historical results should not guide present-day property decisions.