Setting Up the Application Directory and Virtual Environment
Begin by connecting to your server and creating a dedicated folder for your application code. In this example, we use the default userec2-user on an AWS EC2 instance:
Using a virtual environment ensures that the package dependencies for your Flask application do not interfere with other applications on your server.
Configuring the systemd Service
To ensure that your Flask application runs automatically and utilizes the virtual environment, create a systemd unit file. This file instructs systemd on how to manage your service. Follow these steps:- Create a file named
flask-app.serviceunder/etc/systemd/system. - Add the following content to the file:
Explanation of the Service File
-
[Unit] Section
- Description: A brief description of the service.
- After=network.target: Ensures the service starts only after the network is initialized, which is critical for web applications.
-
[Service] Section
- User and Group: The application runs under the
ec2-useraccount. Adjust these values based on your server’s configuration. - WorkingDirectory: Specifies where the application code is located.
- Environment: Sets the
PATHto the virtual environment’sbindirectory, ensuring the correct Python interpreter and dependencies are used. - ExecStart: Launches the application using the Python interpreter from the virtual environment.
- User and Group: The application runs under the
-
[Install] Section
- WantedBy=multi-user.target: Configures the service to start when the system reaches the multi-user runlevel, which is standard for servers without a graphical interface.
Make sure your
app.py file is located in the /home/ec2-user/app/ directory and that it is configured correctly to run your Flask application.Reloading systemd and Starting the Service
After creating or modifying your systemd service file, reload the systemd configuration, enable the service to launch on boot, and start the service immediately:Configuring Network Access
Ensure that your server’s firewall or security groups (for AWS users) allow traffic on the application’s designated port. For example, if your application listens on port 5000, make sure this port is open to allow external access.If your server’s firewall or security groups are not configured correctly, the Flask application might not be accessible from outside, even if it is running.
Summary
In this guide, you learned how to deploy your Flask application by:- Setting up the application directory and Python virtual environment.
- Configuring a systemd service to automate the application startup.
- Reloading systemd and starting the service.
- Adjusting network access to allow incoming traffic.