Your Search Bar For Shrewd Tips

How To Close Uvicorn


Knowing how to close Uvicorn correctly helps you stop a development server, deploy an application safely, or troubleshoot a port that will not become available. In most cases, you can shut down Uvicorn with a keyboard interrupt or a termination signal. The right method depends on whether Uvicorn is running in a terminal, under a process manager, inside a container, or as part of a Python program.

This guide explains how to stop Uvicorn gracefully, what to do when it appears stuck, and how to prevent common shutdown problems. It also covers background processes, multiple workers, and ways to confirm that the server has exited.

What Happens When Uvicorn Shuts Down?

Uvicorn is an ASGI server commonly used to run applications built with FastAPI, Starlette, and other ASGI frameworks. Closing it is more than just making the terminal command disappear. A graceful shutdown gives the server a chance to stop accepting new connections, finish active requests where possible, and run the application’s shutdown or lifespan cleanup tasks.

When Uvicorn receives a supported shutdown signal, it begins its shutdown procedure. Depending on the application and configuration, that process may include closing network connections, waiting for tasks to finish, and running cleanup code. This is especially important if your application uses database connections, background tasks, or other resources that should be released cleanly.

How to Close Uvicorn in a Terminal

If you started Uvicorn directly in a terminal, the simplest way to stop it is to focus that terminal and press Ctrl+C. This sends an interrupt to the foreground process. Uvicorn handles the interrupt and attempts to shut down gracefully.

For example, if you started the server with this command:

uvicorn main:app --reload

Press Ctrl+C in the same terminal window. You should see shutdown messages in the output, followed by your command prompt. The exact messages vary by Uvicorn version, application, and logging configuration.

Use the terminal where the server is running. Pressing Ctrl+C in a different terminal will not normally stop the Uvicorn process. If you launched the server in an integrated terminal in an editor, click that terminal first so it receives the keyboard shortcut.

Stop Uvicorn with a Signal on Linux or macOS

If Uvicorn is running in the background or you cannot access its original terminal, you can send a termination signal to its process. On Linux and macOS, SIGTERM is generally the preferred signal for requesting a graceful stop.

First, find the relevant process. For example, you can search for Uvicorn processes with:

ps aux | grep '[u]vicorn'

Review the output carefully and identify the process ID, or PID, belonging to the server you intend to stop. Then send it a termination signal:

kill -TERM 12345

Replace 12345 with the actual PID. You can also use kill 12345, because kill sends SIGTERM by default on common Unix-like systems. Allow time for Uvicorn and the application to finish their shutdown work before taking further action.

Avoid using broad commands such as pkill -f uvicorn unless you are certain that every matching process should stop. A broad match can terminate unrelated servers or development sessions. Identifying the correct PID first is safer.

When to Use SIGKILL

If a process does not respond to SIGTERM after a reasonable wait, you may need to force it to stop. On Linux and macOS, SIGKILL can be sent with:

kill -KILL 12345

This signal cannot be handled by the application, so Uvicorn cannot perform its normal cleanup. Active requests may be cut off, and application resources may not be released cleanly. Use SIGKILL only as a last resort, such as when the process is genuinely stuck and a graceful termination has failed.

Before forcing a stop, check the Uvicorn logs and allow for long-running requests or shutdown hooks. If graceful shutdown regularly takes too long, investigate the application’s background tasks, database cleanup, and request handling rather than relying on a force kill.

Close Uvicorn on Windows

When Uvicorn runs in a Windows Command Prompt or PowerShell window, press Ctrl+C in the window where it was started. This is the standard way to interrupt a foreground server and request that it stop.

If the process is running elsewhere, you can locate it with Windows tools such as Task Manager or PowerShell. To find processes that are listening on a particular port, run:

Get-NetTCPConnection -LocalPort 8000

Note the owning process ID shown in the results, then inspect it before stopping it. You can request that a process close with:

Stop-Process -Id 12345

Use the correct PID in place of 12345. Stopping a process through system tools may not provide the same graceful behavior as interrupting Uvicorn in its terminal. Confirm that the process is the Uvicorn server you want to close before using this method.

How to Stop Uvicorn Started from Python

If your program starts Uvicorn through its Python API, you can request shutdown by setting the server’s should_exit property. This approach is useful when your own application controls the server lifecycle and needs to stop it in response to an event.

import asyncio
import uvicorn

async def run_server():
    config = uvicorn.Config("main:app", host="127.0.0.1", port=8000)
    server = uvicorn.Server(config)

    server_task = asyncio.create_task(server.serve())

    # Run your application logic here.
    await asyncio.sleep(5)

    server.should_exit = True
    await server_task

asyncio.run(run_server())

In this example, the server runs as an asynchronous task. Setting server.should_exit requests that it stop, and awaiting server_task lets the shutdown finish before the program exits. In a real application, replace the sleep with the condition or event that should trigger shutdown.

For example, you might wait for an asyncio.Event and then request that Uvicorn stop. Keep the control flow on the same event loop where practical, and avoid abruptly terminating the Python process while the server is still serving requests. The available details can vary between Uvicorn versions, so check the documentation for the version installed in your environment.

Shutting Down Uvicorn with Multiple Workers

When you start Uvicorn with multiple workers, such as with --workers 4, a process manager coordinates the worker processes. Stop the main Uvicorn process or use the service manager that launched it rather than trying to kill worker processes one by one. The manager can then coordinate the shutdown and clean up its child processes.

uvicorn main:app --workers 4

If Uvicorn is managed by a system service, container runtime, or deployment platform, use that tool’s normal stop command. Stopping only one worker can leave the manager running, while terminating the wrong process can interrupt other applications. Always identify which process owns the server before sending signals.

Close Uvicorn Gracefully in Docker and Production

For a Uvicorn server in Docker, stop the container through Docker rather than reaching inside to kill an arbitrary process. For example:

docker stop my-api

Docker sends the container’s configured stop signal and waits for its grace period before forcefully terminating it. Make sure the container’s main process receives the signal. If a shell script starts Uvicorn without replacing itself, the signal may reach the shell instead of the server. Use a startup command that ultimately runs Uvicorn as the main process, or use exec in a shell entrypoint.

In production, use the stop or restart command provided by your process manager, such as systemd or a container orchestrator. A managed shutdown is easier to monitor and helps ensure the right process receives the signal. Configure the manager’s stop timeout to allow enough time for Uvicorn and your application to finish cleanup.

Configure the Graceful Shutdown Timeout

Some requests or background tasks may take longer to finish than your deployment platform’s default wait period. Uvicorn provides a graceful shutdown timeout option that can help limit how long it waits for tasks to complete. You can set it from the command line, for example:

uvicorn main:app --timeout-graceful-shutdown 20

The value is a number of seconds. Choose a timeout that fits your application’s expected workload and the stop timeout set by the process manager or container platform. If the outer platform gives the process less time than Uvicorn needs, it may force termination before graceful shutdown finishes.

A longer timeout does not guarantee that every operation will complete. It gives the server more time to shut down, but your application should still handle cancellation and release resources reliably. Check the help output for your installed Uvicorn version to confirm available options:

uvicorn --help

What to Do If the Uvicorn Port Remains in Use

After closing Uvicorn, you might see an error saying that the address or port is already in use when you try to start it again. This can mean the original server is still running, another process is using the same port, or the operating system has not yet released the connection state. Do not assume that an error means Uvicorn itself is still running.

Check which process is listening on the port. On Linux, for example, you can use:

ss -ltnp | grep ':8000'

On macOS, a common option is:

lsof -i :8000

Replace 8000 with your configured port. If the output identifies a Uvicorn process, stop the correct process gracefully. If it identifies a different application, decide whether that application should be stopped or whether you should run Uvicorn on another port.

Common Uvicorn Shutdown Mistakes to Avoid

  • Closing the terminal window instead of stopping the server: Depending on how the process was launched, closing the window may interrupt it without giving you a clear view of the shutdown. Use Ctrl+C or your process manager’s stop command.
  • Using a force kill too early: Start with a graceful interrupt or termination signal. Use a forceful signal only if the process remains unresponsive.
  • Killing the wrong PID: Confirm the process command and PID before stopping it. This is particularly important on a machine hosting multiple applications.
  • Stopping workers individually: With multiple workers, stop the parent process or manager so it can coordinate the worker shutdown.
  • Ignoring application cleanup: Make sure your application’s lifespan shutdown logic completes important cleanup, such as closing database connections or stopping background services.
  • Setting mismatched timeouts: The process manager’s stop grace period should be long enough for Uvicorn’s graceful shutdown to run.

How to Confirm Uvicorn Has Closed

When you stop a foreground server, the clearest sign is that Uvicorn’s terminal output has ended and the shell prompt has returned. For background services, check the process manager’s status or confirm that the relevant PID no longer exists. You can also check whether the server’s port is still listening.

If the application has a shutdown hook, add appropriate logging there. A log message from that hook can confirm that the application reached its cleanup stage. Avoid logging sensitive information, and remember that the absence of a particular message does not always prove that shutdown failed; logging levels and handlers may affect what appears.

Conclusion

To close Uvicorn in a terminal, press Ctrl+C in the window running the server. For a background process on Linux or macOS, identify its PID and send SIGTERM. For Python-managed servers, set server.should_exit and wait for the server task to finish. In Docker or production, use the relevant container or process manager’s stop command.

Prefer graceful shutdown because it gives Uvicorn and your application time to finish work and release resources. If the server does not stop, inspect its process and logs, check the graceful shutdown timeout, and use a forceful termination only as a last resort. These steps make it easier to stop Uvicorn safely and resolve common port and process issues.


Disclaimer: Articles are written by Humans, AI or Both. Verify Important information.

Shrewdnia

Shrewdnia

Shrewdnia is a destination for curious minds seeking clarity, knowledge, and informed perspectives. Through insightful articles and practical guides our passionate team explores a wide range of topics designed to help readers understand the world around them, make smarter decisions, and stay informed in an ever-changing landscape.


💡 Every question sparks discovery, and every perspective enriches the conversation. Share your thoughts and insights in the comments 👇

Back to blog

Leave a comment

JOIN THE SHREWDNIA COMMUNITY FORUM

What do you think?

Have an opinion, experience, or question about this topic? Join the Shrewdnia Forum and share your thoughts with other readers.

Join the Forum →