A FastAPI-based service for securely executing Python code inside a Docker container. This project allows you to submit Python code dynamically, execute it in an isolated environment, and return the results.
- Dynamic Code Submission: Submit Python code via a REST API.
- Secure Execution: Code runs inside a Docker container to ensure isolation.
- Flexible Port Configuration: Port can be customized using environment variables.
- Rich Feedback: Provides output, logs, and error messages for submitted code.
mixed_docker_execution/
├── Dockerfile # Defines the Docker container
├── app/ # Application code
│ ├── main.py # FastAPI main application
│ ├── executor.py # Code execution logic
├── host_code/ # Mounted directory for code execution
│ ├── sample_script.py # Example Python script
├── requirements.txt # Dependencies
└── README.md # Project documentation
- Docker installed (Download Docker)
- Python 3.9+ (optional, for testing with the
requests
library)
-
Clone the Repository:
git clone <repository_url> cd mixed_docker_execution
-
Build the Docker Image:
docker build -t mixed-docker-executor .
-
Run the Container:
docker run --rm -v $(pwd)/host_code:/usr/src/app/host_code -p 22499:22499 mixed-docker-executor
Submit Python code dynamically using curl
:
curl -X POST "http://<host_ip>:22499/submit_code" \
-H "Content-Type: application/json" \
-d '{"code": "print(\"Hello from FastAPI!\")"}'
You can also use Python to send a POST request:
import requests
url = "http://<host_ip>:22499/submit_code"
headers = {"Content-Type": "application/json"}
data = {"code": 'print("Hello from FastAPI!")'}
response = requests.post(url, headers=headers, json=data)
print(response.json())
If the code executes successfully, you should receive:
{
"status": "success",
"output": "Hello from FastAPI!\n",
"error": ""
}
If there's an error in the code:
{
"status": "success",
"output": "",
"error": "SyntaxError: unexpected EOF while parsing"
}
- Customizing the Port:
The default port is
22499
. You can override it using thePORT
environment variable:docker run --rm -e PORT=3000 -p 3000:3000 mixed-docker-executor
To test the service:
- Start the Docker container as described above.
- Submit test cases using the provided
curl
or Python examples.
- The service currently supports only Python scripts.
- Execution is limited to single-file Python code.
- Add support for other programming languages.
- Implement authentication for API endpoints.
- Enhance logging and debugging capabilities.
This project is licensed under the MIT License. See LICENSE
for details.
If you encounter any issues or have suggestions for improvement, feel free to open an issue or submit a pull request!