Step 1: Create the FastAPI Application
Create a file named main.py and add the following code:
python Copy
from fastapi import FastAPI # Import FastAPI framework
app = FastAPI() # Create FastAPI instance
@app.get("/") # Define a simple API endpoint
def read_root():
return {"message": "Hello, FastAPI with Docker!"} # Returns a JSON response
✅ This script starts a FastAPI web server with one route /.
Step 2: Create a requirements.txt File
Create a requirements.txt file to list dependencies:
fastapi
uvicorn
✅ This ensures fastapi and uvicorn are installed inside the container.
Step 3: Write the Correct Dockerfile
Create a Dockerfile to containerize the application.
FROM python:3.9 # Use an official Python image as the base
WORKDIR /app # Set the working directory inside the container
COPY requirements.txt . # Copy the dependencies file and install them
RUN pip install --no-cache-dir -r requirements.txt
COPY . . # Copy the application code into the container
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"] # Run
Uvicorn server to start FastAPI (this keeps the container running)
✅ Key Fix:
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"] ensures Uvicorn
keeps running, preventing the container from stopping.
Step 4: Build the Docker Image
Run the following command in the terminal:
docker build -t fastapi-app . ✅ This builds a Docker image named fastapi-app.
Step 5: Run the Docker Container
Start the container with:
docker run -d -p 8000:8000 --name fastapi-container fastapi-app
✅ Explanation:
-d: Runs the container in detached mode (in the background).
-p 8000:8000: Maps container port 8000 to the host’s port 8000.
--name fastapi-container: Names the container.
fastapi-app: Uses the built image to create the container.
Step 6: Verify That the Container is Running
Check active containers:
docker ps ✅ If the container is running, you will see fastapi-container in
the list.
Step 7: Test the FastAPI Application
Test the FastAPI server using:
curl http://localhost:8000/
or open http://localhost:8000/ in a browser.
✅ Expected Output:
json
Copy
Edit
{"message": "Hello, FastAPI with Docker!"}
Step 8: Debugging (If Needed)
If the container is not working, check logs:
nginx
Copy
Edit
docker logs fastapi-container
✅ This helps to diagnose errors and fix any issues.
Conclusion
The container was exiting because Uvicorn was not running as a persistent process.
By setting CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"], we
ensure that Uvicorn keeps running, preventing the container from stopping.
Now, the FastAPI application runs successfully inside Docker without exiting. 🚀