Alters Dev - Easier and Faster

Create Web App with Docker

Creating web applications with Docker involves containerizing your web application, which allows you to package your application and its dependencies into a single unit that can be easily deployed and scaled. Here's a step-by-step tutorial on how to create a simple web application with Docker:

Step 1: Create a Simple Web Application

For this tutorial, we'll create a basic "Hello, World!" web application using Python and Flask. You can replace this with your own web application code if needed.

Create a folder for your project and add the following files:

`app.py` - Your web application code:
python
        
from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello():
    return "Hello, World!"

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)
        
    
`requirements.txt` - List of Python dependencies:
txt
        
Flask==2.0.1
        
    

Step 2: Dockerfile

Create a `Dockerfile` in the same project folder to define how your application should be containerized:

Dockerfile
        
# Use an official Python runtime as a parent image
FROM python:3.8

# Set the working directory in the container
WORKDIR /app

# Copy the current directory contents into the container at /app
COPY . /app

# Install any needed packages specified in requirements.txt
RUN pip install --no-cache-dir -r requirements.txt

# Make port 5000 available to the world outside this container
EXPOSE 5000

# Run app.py when the container launches
CMD ["python", "app.py"]
        
    

This Dockerfile sets up a Python environment, installs Flask, and runs your `app.py` when the container starts.

Step 3: Build Your Docker Image

Open a terminal, navigate to your project folder, and run the following command to build your Docker image:

bash
        
docker build -t my-web-app .
        
    

Replace `my-web-app` with your desired image name.

Step 4: Run Your Docker Container

Now that you have built the Docker image, you can run a container from it:

bash
        
docker run -p 4000:5000 my-web-app
        
    

This command maps port 4000 on your host machine to port 5000 in the container.

Step 5: Access Your Web Application

Open a web browser and visit `http://localhost:4000`. You should see your "Hello, World!" message.

Step 6: Cleanup

When you're done testing, you can stop and remove the container:

bash
        
docker stop <container_id>
        
    

You can find the `container_id` by running `docker ps -a` and then remove it with:

bash
        
docker rm <container_id>
        
    

Conclusion

That's it! You've successfully created a simple web application using Docker. You can extend this tutorial by replacing the Flask app with your own web application code and modifying the Dockerfile accordingly.