How to Build and Deploy a Web App Using Docker
Category: Software Install and Setup
Docker has revolutionized application deployment by providing a lightweight, consistent, and portable way to package applications. If you're new to containerization, this guide will take you through the process of building and deploying a simple web app using Docker, step by step.
1. Install Docker
Before you can start, ensure that Docker is installed on your machine. You can download it from the official Docker website.
Verify the installation by running:
docker --version
2. Create a Simple Web App
For this example, we will use a simple Flask application written in Python.
Create a new directory and inside it, create a file called app.py
with the following content:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return "Hello, Docker!"
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000)
3. Create a Dockerfile
The Dockerfile is a blueprint for building a container image. Create a file called Dockerfile
and add the following content:
FROM python:3.9
WORKDIR /app
COPY . .
RUN pip install flask
CMD ["python", "app.py"]
4. Build the Docker Image
Now, build the Docker image using the following command:
docker build -t flask-app .
Once the image is built, you can list your Docker images with:
docker images
5. Run the Docker Container
Start the container using the following command:
docker run -d -p 5000:5000 flask-app
Now, visit http://localhost:5000
in your browser, and you should see "Hello, Docker!" displayed.
6. Deploy the Web App
To deploy your web app, you can push it to Docker Hub or use cloud platforms like AWS, DigitalOcean, or Kubernetes.
Push to Docker Hub:
docker tag flask-app username/flask-app
docker push username/flask-app
Conclusion
With Docker, building and deploying web applications has never been easier. By following these steps, you can containerize any web application and deploy it anywhere. For more advanced setups, consider using Docker Compose for multi-container applications. For more resources, check out the official Docker documentation.