From Code to Cloud: Deploying Your Python App with Bunnyshell
Tags: beginners, webdev, python, devops
Published: 2023-12-11 11:54:17

Welcome to the exciting journey of transitioning your python application from code to the cloud! We will take you step-by-step through the process of utilizing Bunnyshell to launch your python application in this blog.

As an **Environments-as-a-Service** platform, Bunnyshell enables full-stack environment creation and administration easier for development, staging, and production.

### 1\. Creating a FastAPI app

In your designated directory, create a new folder named `bunny-pyapp`. This will serve as the home for your API project. Make a file called `app.py` inside the `bunny-pyapp` folder. The main functions of your API will be stored in this file. To prevent cross-origin resource sharing (CORS) issues when utilizing your API, incorporate the CORS Middleware in your `app.py`. This is an important step that guarantees your API and other applications communicate with one other seamlessly.

```python
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware 
import uvicorn 

app = FastAPI() 

origins = ['*']

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
) 

@app.get("/")
async def root():
    return {"message": "Hello from FastAPI"} 

if __name__ == "__main__":
    uvicorn.run(app, host='0.0.0.0', port=8000)
```

After our script is finished, we'll check to see if the FastAPI is accessible.

```bash
$ python3 app.py
```

Point to [`http://localhost:8000/`](http://localhost:8000/) after executing the following command to see the "*Hello from Fastapi*" message. A Swagger User Interface (UI) will appear when you route to [`http://localhost:8000/docs`](http://localhost:8000/docs), assisting in the testing of your endpoints.

### **2\. Creating a requirements.txt**

To make it easier for us to install all of our packages, we now generate a `requirements.txt` file inside the "*bunny-app"* folder. You can use the command pip `freeze > requirements.txt`, or you can manually add them to the requirements.txt file.

```bash
fastapi
uvicorn
gunicorn
```

### **3\. Signing to BunnyShell**

Open the BunnyShell web page by pointing to this [`https://www.bunnyshell.com/`](https://www.bunnyshell.com/) .Once the page is loaded click on to **Log in** and select **'Environments as a Service'**.The page will reroute to the BunnyShell Dashboard upon successful login.

Our deployment process utilizes the power of Kubernetes pods, allowing for efficient scaling and resource management. Docker Compose is a well-known containerization tool, we use its familiar format to make the configuration of these pods easy for developers who are accustomed to it. It is also possible to configure your Kubernetes environment for easy deployment using Helm Charts, which are easily accessible.


![bunnyshell](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mt5efvcqvfgzwssqc4fi.png)


### **4\. Creating a Dockerfile**

It's time to build the `Dockerfile`, which will serve as the blueprint for creating your bunny-app container image, within your project folder. To shape your container and get it ready for cloud deployment, add the following content:

```yaml
# Specify base image
FROM python:3.9

# Set working directory
WORKDIR /app

# Install dependencies
COPY requirements.txt .
RUN pip install -r requirements.txt

# Copy application code
COPY . .

# Expose application port
EXPOSE 5000

# Define command to run app
CMD ["python3", "app.py"]
```

This Dockerfile provides the foundation for building your bunny-app container image. The application code is copied, the base image is defined, required dependencies are installed, the application's port is exposed, and the command to run when the container starts is specified. Remember to update the Dockerfile with the details of your specific project requirements.

### **5\. Creating a Docker compose**

Now is the time to construct the `docker-compose.yaml` file within your project directory. This vital configuration file orchestrates the deployment and management of your bunny-app within docker containers. You may clearly outline the path your application will take to the cloud by specifying the services, ports, networks, volumes, and other variables.

```yaml
version: '3.7'
services:
  bunnyapp:
    # Build the image from the local Dockerfile
    build: ./
    
    # Expose port 8000 for internal communication 
    ports:
      - 8000:8000

    # Define restart policy to automatically restart the service in case of failures
    restart: always
```

### **6\. Push Code to Github repository**

Create a repository of your choice. In this tutorial I'll be using `bunny-app` as repository name. To seamlessly push your code to GitHub, follow these steps in your `bunny-pyapp` folder.

```yaml
git init
git remote add origin <git_url>
git add .
git commit -m "first commit"
git push -u origin master
```

Upon successfully pushing your bunny-app code to GitHub, head over to your repository to verify the contents.


![github](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ftzxkjzh6x3t4qtcv21d.png)


### **7\. Configuring Deployment**

Locate the "**Create environment"** button, which is usually located in the interface's right corner. .A pop-up window will appear. Give your environment a name that explains such as `bunny-app` or a custom name reflecting your project. Press the **"Create environment"** button one more time. This will start Bunnyshell creating your customized environment.


![create environment](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zb4zwxjfz4f13w782jgi.png)


Click on **"Get Started"** button and choose with "Docker Compose" or "Package JSON" to start your configuration.


![bunnyshell](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7v31ap823phmvbzpp7wf.png)



Select your Git account (e.g., GitHub) and provide the repository name followed by branch and root application path. This allows Bunnyshell to access your code and build the environment.


![bunnyshell](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/77phor9t9tis27pebba5.png)



Based on the organization of your project, Bunnyshell will automatically produce environment components. Inspect these elements carefully, taking note of the ports, volumes, and services. Adjust them as necessary to meet your unique needs.To move on to the last configuration stage, click "Continue".


![bunnyshell](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2hz224gwobswwkpfor9l.png)

Reviewing the entire environment configuration, including resource limitations, environment variables, and health checks, is possible here. Optimize the performance and resource utilization of your bunny-app by making any necessary adjustments. Click "Create Application" to finalize the configuration and build your application.


![bunnyshell](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fb5oi3vinb3eryrx1itp.png)


> Note : Check over your context path for your build

Click the "Deploy" button located in the upper right corner once the project is finished. For deployment, choose the "Bunnyshell Cluster" that is offered by default. Change **"Environment URL"** to `pythonapp` or any other name that better represents your project. The public URL for your deployed application will be this one.


![bunnyshell](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/za1vuj32dj43p0dfa948.png)


Click on the three dots menu beside your environment name and select `Pipeline logs` to view the detailed deployment process in real-time. This log will reveal any potential errors or warnings during the build and deployment stages.


![bunnyshell](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g3gqa03xay9u5pxr17ig.png)



Your application logs will appear simultaneously in the right panel of your Bunnyshell interface. These logs, which contain error messages, debug information, and application activity, provide insightful information about the behavior of your application during runtime.


![bunnyshell](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5kd5p0dca3noygqqs7va.png)



Click the "Deployments" option from the dropdown menu beneath your "bunnyapp" name for more in-depth debugging and analysis. This will show the specifics of the Kubernetes deployment, including the logs of each individual container.


![bunnyshell](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rnme7n5moika02zb50cr.png)


Access your environment by navigating to the URL [`https://bunnyapp-pythonapp.bunnyenv.com/`](https://bunnyapp-pythonapp.bunnyenv.com/). You should observe a displayed message on the page.


![bunnyshell](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lbch9a0cstmxyeiqidz6.png)



Hurray! Your Python app has successfully taken flight on Kubernetes pods with help of Bunnyshell environments.You may run applications created with different technology stacks thanks to Bunnyshell's power, which goes much beyond.