Deploying a Model API to AWS: ECR, Secrets Manager, CloudWatch and Fargate, Then Teardown
The route a ticket priority API takes to AWS: the image to ECR, the key to Secrets Manager, logs to CloudWatch, and the container on ECS Fargate, in the right order. Then the checks (health, 401, predictions, logs) and a teardown that actually stops the bill.
What you will learn
- Name the four AWS pieces of the route and the one job of each: ECR, Secrets Manager, CloudWatch, ECS on Fargate
- Order the deploy steps so the task has its image, key and log group before it starts
- Check a running service with a health call, a prediction and the log lines
- Tear everything down in order, and know why a budget alert alone won't stop the bill
Before you start
- Containerising a Model API: A Dockerfile
- IaaS, PaaS, Containers or Serverless?
Our ticket priority API is trained and packed into a container. Now it needs somewhere to sit that isn't our own machine. This article walks the route it takes to AWS: the image goes into a registry, the key goes into a safe, and a managed service runs the container. Then how you check it, and how you tear it down so nothing keeps billing.
deploy.py; no AWS account was used for this lesson. Everything else (the image, the calls, the logs, the teardown) ran for real, locally and in Docker. The tickets are synthetic.From the garage to the high street
Think of a shop you've been running from your garage. You move it to the high street: same shop, proper address.
- The stock goes into a storeroom. That's ECR, which holds your image.
- The shopfront keeps it open. That's Fargate.
- The open sign on the door is your health check, and the day book is your logs.
- When the lease ends, you clear out. Otherwise the rent keeps coming.
What we're shipping
FROM python:3.13-slim
WORKDIR /srv
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app.py features.py train_model.py ./
COPY data data
RUN python train_model.py model.joblib
USER nobody
EXPOSE 8000
HEALTHCHECK CMD python -c \
"import urllib.request as u; \
u.urlopen('http://localhost:8000/health')"
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", \
"--port", "8000"]
RUN python train_model.py trains inside the build, so the image carries its model with it. USER nobody means the process doesn't run as root. The health check calls /health on port 8000. Built in Docker, the image is 685 MB, whoami inside it says nobody, and Docker reported it healthy. (For the Dockerfile itself line by line, see containerising a model API.) This one box is what we move.
Four pieces, one job each
- Amazon ECR, the container registry. You push the image there once, and AWS pulls it from there.
- Secrets Manager, the safe for the API key, so the key never sits in the image.
- CloudWatch, the day book. Whatever the container prints lands in a log group.
- ECS on Fargate, the shopfront. It runs the container with no server to patch: it pulls the image, reads the key and writes the logs.
Why Fargate and not a VM or a function? That choice is made in IaaS, PaaS, containers or serverless. Why AWS? Because it's what this team knows; see which cloud for what.
What the task needs comes first
deploy.py plan prints the route. Nothing is run; it's the order written down:
python deploy.py plan
1 ecr aws ecr create-repository --repository-name ticket-api
2 push docker push ACCT.dkr.ecr.REGION.amazonaws.com/ticket-api:1
3 secret aws secretsmanager create-secret --name ticket-key --secret-string $KEY
4 logs aws logs create-log-group --log-group-name /ecs/ticket-api
5 service aws ecs create-service --launch-type FARGATE --desired-count 1 --task-definition ticket-api
6 budget aws budgets create-budget --budget file://budget.json
teardown, in this order:
aws ecs update-service --desired-count 0
aws ecs delete-service --force
aws ecr delete-repository --force
aws secretsmanager delete-secret --force-delete-without-recovery
aws logs delete-log-group
- Create the repository and push the image.
- Store the key.
- Create the log group.
- Start the service on Fargate. The task definition fixes the size: 256 CPU units and 512 MB, with the key from the secret and one running copy.
- A budget, so the bill never surprises you.
Why the secret and the logs before the service? Because the task needs both the moment it starts. The app refuses to start without a key:
# the secret arrives as an environment variable
KEY = os.environ.get("API_KEY", "")
if not KEY:
log(level="error", msg="API_KEY is not set")
sys.exit(1)
When the container started in Docker with no key, it stopped at once with exit code 1:
{"level": "error", "msg": "API_KEY is not set"}
A task on AWS fails the same way. So what the task needs comes first.
A permission policy with no wildcards
The task's role should be able to do exactly three things: pull this one image, read this one secret, and write its own logs. policy.json says so:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "PullImage",
"Effect": "Allow",
"Action": ["ecr:GetAuthorizationToken",
"ecr:BatchGetImage",
"ecr:GetDownloadUrlForLayer"],
"Resource": "arn:aws:ecr:REGION:ACCT:repository/ticket-api"
},
{
"Sid": "ReadOneSecret",
"Effect": "Allow",
"Action": ["secretsmanager:GetSecretValue"],
"Resource": "arn:aws:secretsmanager:REGION:ACCT:secret:ticket-key-*"
},
{
"Sid": "WriteOwnLogs",
"Effect": "Allow",
"Action": ["logs:CreateLogStream", "logs:PutLogEvents"],
"Resource": "arn:aws:logs:REGION:ACCT:log-group:/ecs/ticket-api:*"
}
]
}
deploy.py policy checks a policy file for * actions and resources:
python deploy.py policy
3 statements, 0 problems
Now the same check on wide.json, a test policy with a single statement that allows every action on every resource:
python deploy.py policy wide.json
too wide: AllowEverything: action *
too wide: AllowEverything: resource *
1 statements, 2 problems
Is it working?
You call it and read its logs. Here's the app run locally on port 8123 with python deploy.py up. Its model scored 0.6820 test accuracy on the synthetic tickets.
@app.get("/health")
def health():
return {"status": "ok", "model": MODEL_PATH.name}
@app.post("/predict")
def predict(t: Ticket, x_api_key: str = Header("")):
if x_api_key != KEY:
log(level="warn", msg="rejected: bad key")
raise HTTPException(401, "bad key")
row = pd.DataFrame([t.model_dump()])
p = float(model.predict_proba(row)[0, 1])
label = "high" if p >= 0.5 else "low"
log(level="info", msg="predicted", priority=label)
return {"priority": label, "p_high": round(p, 4)}
| Call | Status | Body |
|---|---|---|
GET /health | 200 | {"status": "ok", "model": "model.joblib"} |
POST /predict, no key | 401 | {"detail": "bad key"} |
POST /predict, with key | 200 | {"priority": "low", "p_high": 0.2273} |
POST /predict, a second ticket | 200 | {"priority": "high", "p_high": 0.8894} |
And the log tells the whole story:
{"level": "info", "msg": "model loaded"}
{"level": "warn", "msg": "rejected: bad key"}
{"level": "info", "msg": "predicted", "priority": "low"}
{"level": "info", "msg": "predicted", "priority": "high"}
On AWS you'd make the same calls against the service's address and read these same lines in the CloudWatch log group. (A hardened version of this API, with input limits and a readiness check, is in a production FastAPI for an ML model.)
End of the lease
Now the part that stops the bill. Locally:
python deploy.py down
port 8123 is closed
runs folder removed
down stops the process, then asks for /health again. Nothing answers, so the port is closed, and the runs folder is removed.
On AWS, the teardown has an order too (the end of the plan above):
desired-count 0first, so the tasks stop.- Delete the service.
- Delete the repository.
- Delete the secret.
- Delete the log group.
And here's a trap: a budget alert only warns you. It doesn't switch anything off. For the rates, check the Fargate pricing page. Then look again, the same way we checked the port. Teardown isn't finished when the command ends. It's finished when something tells you it's gone. Cost thinking goes deeper into what this route costs.
Recap
| Part | What to remember |
|---|---|
| The route | ECR for the image, Secrets Manager for the key, CloudWatch for the logs, Fargate to run it |
| The order | What the task needs (image, secret, logs) before the service; a budget too |
| The checks | Health 200, no key 401, predictions 200, and the log lines |
| The teardown | Desired count 0, then service, repository, secret, log group; then check it's gone |
Try it yourself: open deploy.py, move the budget line to the top of PLAN, and run python deploy.py plan.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Managed ML Platforms: What SageMaker, Vertex AI and Azure ML Give You, and Tie You To
Next →Cloud Cost Thinking for ML: Size x Count x Hours x Rate, and Three Decisions Worth Ten Times
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Python Virtual Environments: One Project, One Toolbox
Why every Python project gets its own virtual environment: two projects that need different versions of requests, python -m venv .venv, activation, pip install and the PyCharm setting that activates it for you.
Git and GitHub Fundamentals: Commits, Branches, Push and Pull
The Git you use every day, on a tiny hello-ml project: commits as save points, the staging area, a branch merged with a fast-forward, then push, clone, pull and pull requests with a teammate.
Testing a FastAPI App with pytest: Three Small Tests
A tiny FastAPI app with a Hello World route and a name route that refuses numbers, three pytest tests that check it, and what happens when the validation is deleted by mistake.
Config and Logging Instead of Hard-Coded Values in ML Training
Take the hard-coded values out of a car price training script: one config.toml read with tomllib, logging with levels and a run id on every line, and secrets read from the environment. Same RMSE, 2195, before and after.