Deploy Flaks Using Docker On Ubuntu

Deploy Flaks Using Docker On Ubuntu

To deploy a Flask application using Docker on Ubuntu, you'll need to follow these general steps:

  1. Install Docker on your Ubuntu server if you haven't already.

  2. Create a Flask application or use an existing one.

  3. Write a Dockerfile to define the Docker image.

  4. Build the Docker image.

  5. Run a Docker container based on the image.

Here's a basic example to get you started:

1. Install Docker on Ubuntu

You can follow the official Docker documentation to install Docker on Ubuntu: Get Docker Engine - Community for Ubuntu

2. Create a Flask Application

Create a Flask application or use an existing one. For example, you could have a Flask app in a file named app.py:

from flask import Flask

app = Flask(__name__)

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

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')

3. Write a Dockerfile

Create a file named Dockerfile in the same directory as your Flask app with the following contents:

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

# Set the working directory in the container
WORKDIR /app

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

# Install Flask and other dependencies
RUN pip install --no-cache-dir Flask

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

# Define environment variable
ENV FLASK_APP=app.py

# Run flask app
CMD ["flask", "run", "--host=0.0.0.0"]

4. Build the Docker Image

Navigate to the directory containing your Dockerfile and build the Docker image:

docker build -t my-flask-app .

5. Run a Docker Container

Once the image is built, you can run a Docker container based on the image:

docker run -p 5000:5000 my-flask-app

Now your Flask application should be running inside a Docker container, and you should be able to access it at http://localhost:5000 or http://<your-server-ip>:5000 if you're running Docker on a remote server.

Did you find this article valuable?

Support Mandeep Singh Blog by becoming a sponsor. Any amount is appreciated!