Okteto with Python
This guide takes the Python Sample App through the whole Okteto workflow, in an application environment in your Kubernetes cluster. The Python Sample App is a hello world FastAPI service. Its page shows a message, the Python version, and the pod that serves it.
The sample is small, but its configuration is optimized, so you can use it as a reference for your own Python application. Along the way, the guide points out what makes each step fast in a Python project: the cache mount that the build and the tests share, the ignore files that keep every upload small (.dockerignore, .oktetoignore, and .stignore), and Uvicorn and the Python Debug Server for hot reload and debugging from PyCharm.
Prerequisites
- The Okteto CLI, installed and configured to access your Okteto instance. See the installation guide.
- To debug the application: PyCharm Professional, which includes the Python Debug Server.
Clone the Python Sample App and move into its folder. Every command in this guide runs from there:
git clone https://github.com/okteto/python-getting-started
cd python-getting-started
Build
The Python Sample App uses two container images. dev is the image you develop in: it has Python, the build tools that pip needs to compile packages, and the tools to reload and debug the application. hello-world is the production image: a slim Python image with nothing but the application and its dependencies. The build section of the okteto.yml file defines both:
build:
dev:
context: .
target: dev
hello-world:
context: .
target: prod
depends_on:
- dev
Both images come from the same Dockerfile. target picks the stage each image builds, and depends_on tells Okteto to build dev first, so hello-world finds its dependencies in the pip cache that dev filled:
FROM python:3.15.2-trixie AS dev
# The cache mounts keep the pip cache in the Okteto Build Service, which
# reuses it between builds. The tests of the Okteto Manifest use the same cache
RUN --mount=type=cache,target=/root/.cache/pip \
pip install pydevd-pycharm==263.7307.329
WORKDIR /usr/src/app
COPY requirements.txt .
RUN --mount=type=cache,target=/root/.cache/pip \
pip install -r requirements.txt
COPY . .
FROM python:3.15.2-slim-trixie AS prod
WORKDIR /usr/src/app
COPY requirements.txt .
RUN --mount=type=cache,target=/root/.cache/pip \
pip install -r requirements.txt
COPY app.py .
COPY static static
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8080"]
The Dockerfile installs pydevd-pycharm, the debugger that connects to PyCharm, and the dependencies in requirements.txt before COPY . ., so a code change doesn't install them again. The dependencies include Uvicorn, the server that runs the application and reloads it in the Development Container.
Every RUN instruction mounts the pip cache (/root/.cache/pip) as a cache mount, which the Okteto Build Service keeps between builds. When a change to requirements.txt runs pip install again, pip downloads only the packages that changed and takes the rest from the cache. The cache holds only the files that pip downloads: the packages themselves are installed in the image, so the application has them at run time.
The build context makes the biggest difference, here and in any application. Every okteto build starts by uploading the Dockerfile's folder to the Okteto Build Service, and the .dockerignore file decides what goes in. The Python Sample App's .dockerignore excludes everything and then allows only what the build reads: requirements.txt, the Python files, and the static folder with the page.
*
!requirements.txt
!*.py
!static
The upload stays small, and a change to any other file, such as the README or k8s.yml, doesn't rebuild the images.
Deploy
okteto deploy first builds the images that aren't built yet. Okteto pushes them to the Okteto Registry and stores their references in the OKTETO_BUILD_DEV_IMAGE and OKTETO_BUILD_HELLO_WORLD_IMAGE variables.
The Python Sample App deploys with a plain Kubernetes manifest. Its deploy section has a single command, which applies k8s.yml with kubectl:
deploy:
- envsubst < k8s.yml | kubectl apply -f -
In k8s.yml, the Deployment's image is the OKTETO_BUILD_HELLO_WORLD_IMAGE variable. envsubst replaces it with the image Okteto built, and then kubectl applies the file.
The deploy has its own ignore file. okteto deploy uploads your folder to the container that runs the command, and the .oktetoignore file decides what goes in. Its deploy section excludes everything except k8s.yml, the only file the command reads, so there's almost nothing to upload. Its destroy section does the same for okteto destroy:
[deploy]
*
!k8s.yml
[destroy]
*
!k8s.yml
To deploy the application, run okteto deploy:
okteto deploy
Okteto builds the two images, runs the deploy command, and prints the application's endpoint:
i Using cindy @ okteto.example.com as context
✓ Image 'registry.okteto.example.com/cindy/python-getting-started-dev:okteto' successfully pushed
✓ Image 'registry.okteto.example.com/cindy/python-getting-started-hello-world:okteto' successfully pushed
i Running stage 'envsubst < k8s.yml | kubectl apply -f -'
Executing command 'envsubst < k8s.yml | kubectl apply -f -'...
deployment.apps/hello-world created
service/hello-world created
Command 'envsubst < k8s.yml | kubectl apply -f -' successfully executed
i Endpoints available:
- https://hello-world-cindy.okteto.example.com
✓ Development environment 'python-getting-started' successfully deployed
Open the endpoint in your browser. The page shows the application's message, the Python version it runs on, and the pod that served the request:
Test
The Python Sample App has unit tests in test_app.py, written with pytest and the FastAPI test client. The test section of the Okteto Manifest defines a test, unit, that runs them:
test:
unit:
image: ${OKTETO_BUILD_DEV_IMAGE}
caches:
- /root/.cache/pip
commands:
- pip install -r requirements-test.txt
- pytest --junitxml=report.xml
artifacts:
- report.xml
The test runs with Remote Execution, in a container inside your cluster. The container starts from the development image, so it has the same Python version and dependencies as the Development Container. The first command installs the test dependencies: requirements-test.txt adds pytest and httpx2, the FastAPI test client's HTTP client, to the dependencies in requirements.txt. If any of the commands exits with a non-zero code, the test fails. When the test finishes, Okteto copies its artifacts, here pytest's JUnit report, to your machine.
The caches entry is the same folder that the Dockerfile mounts, and it's the same cache too: Okteto identifies a cache by its repository, context, and path, and the test and the build share all three. The development image already has the application's dependencies, so pip install only adds the test dependencies. It downloads them on the first run and takes them from the cache on every run after that.
The tests have their own section in the .oktetoignore file, so okteto test uploads only what pip install and pytest read:
[test]
*
!requirements.txt
!requirements-test.txt
!*.py
!static
Run the unit tests with okteto test:
okteto test
i Using cindy @ okteto.example.com as context
i Images were already built. To rebuild your images run 'okteto build'
i Executing test container 'unit'
i Running 'pip install -r requirements-test.txt'
Collecting httpx2==2.16.2 (from -r requirements-test.txt (line 3))
Using cached httpx2-2.16.2-py3-none-any.whl.metadata (10.0 kB)
Successfully installed Pygments-2.21.0 httpcore2-2.16.2 httpx2-2.16.2 iniconfig-2.3.1 packaging-26.3 pluggy-1.7.0 pytest-9.2.0 truststore-0.10.5
✓ Command 'pip install -r requirements-test.txt' successfully executed
i Running 'pytest --junitxml=report.xml'
============================= test session starts ==============================
platform linux -- Python 3.15.2, pytest-9.2.0, pluggy-1.7.0
rootdir: /okteto/src
plugins: anyio-4.16.0
collected 2 items
test_app.py .. [100%]
------------------ generated xml file: /okteto/src/report.xml ------------------
============================== 2 passed in 0.29s ===============================
✓ Command 'pytest --junitxml=report.xml' successfully executed
✓ Test container 'unit' passed
The JUnit report is now in report.xml, in the root folder of the Python Sample App on your machine. Your CI system can read it to show the results of each test.
Running okteto deploy and okteto test after each change is usually fast enough, especially when a coding agent writes and tests the code on its own. With the Okteto skills, the agent runs this loop in its own Namespace and reports back the tests it ran, the application's endpoints, and a link to that Namespace.
Develop
A Development Container feels like developing on your machine: every change you save reloads the application, and you can attach a debugger. When you run okteto up, Okteto replaces the hello-world Deployment with the Development Container, keeps your local files synchronized with it, and runs the development image's hot reload and debugging tools in your cluster. This step is optional: coding agents work well with the okteto deploy and okteto test loop and don't need a Development Container.
While okteto up is running, a coding agent with the Okteto skills stops building, deploying, and testing, and only edits the code: File Sync copies each change to the Development Container, and hot reload applies it to the running application.
The dev Section
The dev section of the Okteto Manifest defines the Python Sample App's Development Container:
dev:
hello-world:
image: ${OKTETO_BUILD_DEV_IMAGE}
command: uvicorn app:app --host 0.0.0.0 --port 8080 --reload
sync:
- .:/usr/src/app
persistentVolume:
enabled: false
reverse:
- 9000:9000
The hello-world key is the name of the Deployment in k8s.yml that the Development Container replaces. This is what each field does:
image: the development image from thebuildsection.command: starts Uvicorn with--reload, which restarts the application every time a.pyfile changes.sync: synchronizes the Python Sample App's root folder with/usr/src/app, the development image's working directory.persistentVolume: disables the Development Container's persistent volume, so there's no volume to create and attach. Okteto synchronizes every file on eachokteto up, and Uvicorn starts the application right away, because the dependencies are part of the development image. The build's cache mount isn't, so apip installin the Development Container downloads its packages again. For a larger project, keep the Development Container's pip cache in a persistent volume. Caches in Development Containers explains how.reverse: forwards port9000of the Development Container to port9000of your machine, where the PyCharm debugger listens.
The third ignore file is .stignore, for File Sync. okteto up synchronizes your folder with the Development Container in both directions, and this file leaves out what shouldn't travel. That's the Git metadata, which is large and only matters on your machine, and the files that Python and pytest generate inside the Development Container, which would otherwise come back to your machine:
.git
__pycache__
/.pytest_cache
/report.xml
.venv
venv
.idea
.vscode
.DS_Store
Hot Reload
Run okteto up to replace the hello-world Deployment with the Development Container:
okteto up
Okteto synchronizes your files and starts Uvicorn, which runs the application in a server process:
i Using cindy @ okteto.example.com as context
i 'python-getting-started' was already deployed. To redeploy run 'okteto deploy' or 'okteto up --deploy'
i Images were already built. To rebuild your images run 'okteto build'
✓ Images successfully pulled
✓ Files synchronized
Context: okteto.example.com
Namespace: cindy
Name: hello-world
Reverse: 9000 <- 9000
INFO: Will watch for changes in these directories: ['/usr/src/app']
INFO: Uvicorn running on http://0.0.0.0:8080 (Press CTRL+C to quit)
INFO: Started reloader process [83] using StatReload
INFO: Started server process [85]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: 10.0.0.12:54442 - "GET /api/info HTTP/1.1" 200 OK
While the page is open in your browser, Uvicorn logs its request to /api/info every second.
Now change the code. Open app.py in your IDE, edit the message on line 9, and save the file:
MESSAGE = 'Built, deployed, and tested on Okteto.'
Okteto synchronizes app.py to the Development Container. Uvicorn notices the change and restarts the server process:
WARNING: StatReload detected changes in 'app.py'. Reloading...
INFO: Shutting down
INFO: Waiting for application shutdown.
INFO: Application shutdown complete.
INFO: Finished server process [85]
INFO: Started server process [109]
INFO: Waiting for application startup.
INFO: Application startup complete.
A moment later, the page in your browser shows the new message. You don't even have to reload it, because the page asks the service for its info every second. Your change is running in your cluster, and you didn't build an image or redeploy the application.
When you're done, press Ctrl+C to stop Uvicorn and exit okteto up.
Debugging with PyCharm
To debug the application, connect it to PyCharm's Python Debug Server. PyCharm listens on port 9000 of your machine, and the debugger in the Development Container, pydevd-pycharm, connects to it: that's the port okteto up forwards from the Development Container to your machine.
The version of pydevd-pycharm must match the build of your PyCharm. Open Run > Edit Configurations, select the Python Sample App's Remote configuration, and check the pip install pydevd-pycharm~=<build> command that PyCharm shows. If the build is different from 263.7307.329, change the version in the Dockerfile and run okteto deploy to rebuild the development image.
The Python Sample App's .idea/runConfigurations/Remote.xml file defines the Remote configuration, a Python Debug Server on port 9000:
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Remote" type="PyRemoteDebugConfigurationType" factoryName="Python Remote Debug">
<module name="python-getting-started" />
<option name="PORT" value="9000" />
<option name="HOST" value="localhost" />
<PathMappingSettings>
<option name="pathMappings">
<list>
<mapping local-root="$PROJECT_DIR$" remote-root="/usr/src/app" />
</list>
</option>
</PathMappingSettings>
<option name="REDIRECT_OUTPUT" value="true" />
<option name="SUSPEND_AFTER_CONNECT" value="false" />
<method v="2" />
</configuration>
</component>
remote-root is the path of the code in the Development Container, the same one as in the sync field of the Okteto Manifest. If you synchronize your code to another path, change remote-root to match.
Open the Python Sample App in PyCharm and debug the Remote configuration. The Debug tool window shows Waiting for process connection.... Start the Remote configuration before the next step, because the application connects to it when it starts.
Run okteto up again if you stopped it. Then uncomment the call to attach() on line 38 of app.py and save the file:
def attach():
import pydevd_pycharm
print('Connecting to debugger...')
pydevd_pycharm.settrace('localhost', port=9000, suspend=False, stdout_to_server=True, stderr_to_server=True)
# uncomment to use PyCharm's remote debugger
attach()
Uvicorn restarts the server process. When the new process imports app.py, attach() connects it to PyCharm through port 9000:
WARNING: StatReload detected changes in 'app.py'. Reloading...
INFO: Finished server process [111]
Connecting to debugger...
INFO: Started server process [112]
INFO: Waiting for application startup.
INFO: Application startup complete.
The Debug tool window shows Connected to pydev debugger:
Now add a breakpoint on line 23 of app.py, the first line of the hello function. The page in your browser asks the service for its info every second, so execution stops at the breakpoint right away, and you can step through the function and inspect its variables. Every time you save a file, Uvicorn starts a new server process, and attach() connects it to PyCharm again.
To end the debugging session, comment out the call to attach() again and save app.py. Then press Ctrl+C to stop Uvicorn and exit okteto up.
Stopping the Development Container
When you finish developing, run okteto down. It stops the Development Container and brings back the hello-world Deployment with the production image:
okteto down
i Using cindy @ okteto.example.com as context
✓ Development container 'hello-world' deactivated
Destroy
To delete the application, run okteto destroy. It removes the Python Sample App's Deployment and Service from your Namespace:
okteto destroy
i Using cindy @ okteto.example.com as context
i Images were already built. To rebuild your images run 'okteto build'
✓ Development environment 'python-getting-started' successfully destroyed
FAQ
How do I set up my own repository the same way?
Use a coding agent with the Okteto skills. Ask it to set up your repository for Okteto: it discovers your services, writes the Okteto Manifest, and validates it with okteto build and okteto deploy.
How do I make builds, deploys, and okteto up faster?
Upload only the files that each command needs: the context upload is key to performance. Every okteto build, okteto deploy, okteto test, and okteto up uploads files from your machine, and three ignore files decide what gets uploaded: .dockerignore for the image builds, .oktetoignore for okteto deploy, okteto test, and okteto destroy, and .stignore for File Sync. A coding agent with the Okteto skills configures them for your application and measures how much faster your builds, deploys, and okteto up get. Optimize Your Application Environment covers these and other optimizations.
Do I need to deploy the whole application in every Namespace?
No. Okteto supports two models, and you choose one for your application:
- Full replica: every service of the application runs in your Namespace. In a monorepo, the
deploysection of the Okteto Manifest deploys every service, as in the quickstart, where one Helm chart deploys the three services of Kube Movies. In a multirepo, each repository has its own Okteto Manifest and lists the other repositories in itsdependenciessection, as in Deploy a Multi-Repo Application with Dependencies. Full replicas are simpler to configure and give you full isolation: nothing one environment does affects the others. Use them for an application with fewer than 20 services. - Overlay Namespace: your Namespace runs only the services you change, and Divert routes every other request to a Shared Namespace that runs the rest of the application. Overlay Namespaces are more cost-effective, faster to deploy, and more reliable, because each environment builds, deploys, and runs only the services it changes. Use them for an application with 20 services or more.
How do I create a Preview Environment of my application for every pull request?
Add a workflow to your CI pipeline that deploys the application in a Preview Environment when a pull request opens or changes, runs okteto test against it, and destroys it when the pull request closes. The workflow uses the Okteto Manifest, so okteto build, okteto deploy, and okteto test work the same way in your CI pipeline, for coding agents, and on developer machines. Follow the guide for GitHub Actions or for GitLab CI/CD.
How do I start each environment with realistic data?
Load the data with a script in your deploy commands, or copy the data of another application environment with a Volume Snapshot, which creates the volumes of your database from a snapshot of its volumes. Data from Volume Snapshots shows how.
How do I create resources outside Kubernetes, such as a cloud database?
Create them in the deploy and destroy commands with your infrastructure as code tool, so every environment gets its own resources. See the Create Cloud Infrastructure with Terraform tutorial, which creates an Amazon S3 bucket for each environment.
Can I access my application environment with kubectl?
Yes. Run okteto kubeconfig to add the credentials of your Okteto Namespaces to your kubeconfig file, and use kubectl as usual: kubectl get pods, kubectl logs, or kubectl describe. See Kubernetes Credentials for how Okteto generates those credentials.