I wanted to check the operation of the GCP load balancer, so I decided to set up a web application on Compute Engine. Originally, the purpose was to verify the load balancer, but I thought it would be better to record the work in the process properly, so I decided to write this article this time.
As the title says, "Build a web application in Python3 + flask environment using Compute Engine". If you are new to GCP, it may be helpful, so please read on if you like: thumbs up:
Building a Compute Engine environment is easy, isn't it? A Linux server can be easily set up by clicking the button.
Create a Compute Engine VM machine from here on the GCP console.
Here ↓ is a reference example of instance setting.
The point is to check "Allow HTTP traffic". Since a web server (flask) is set up, you cannot check the operation from the outside unless you check this.
After that, press the "Create" button and wait a few minutes to start the VM.
Let's SSH to see if it started properly.
Yes, it started successfully: smile:
Now that the VM has started up safely, it's time to set up the Python environment.
First, update apt.
sudo apt update
Python2 series is installed by default in the set up VM.
Python3 series is also installed in this Debian 9 package.
However, pip3 is not installed, so you need to prepare it.
Enable pip3 with the following command.
sudo apt install python3-pip
You can now use pip3. Next, we will install flask with pip3.
pip3 install flask
Install flask with pip3. it's simple.
You can now use flask. Let's check the operation.
Let's prepare a Python script that uses flask to check the operation.
First, create a file with nano (text editor) from the following command.
nano main.py
When the editor opens, copy and paste the script below.
main.py
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, Flask World!!'
if __name__ == '__main__':
app.run(debug=False, host='127.0.0.1', port=5000)
It looks like this ↓
If you can copy
Exit the nano editor by typing.
Start the script created by the following command.
python3 main.py
It is OK if the screen looks like the one below. flask is working.
So far, we have confirmed the operation, but just in case, let's check the response of the web application with the curl command. Make another SSH connection and enter the following command to check the response.
curl 127.0.0.1:5000
Since the port number is 5000, type curl with the above command.
The string "Hello world" was responded properly, so you can confirm that the web application is working.
What did you think? Neither task is too difficult, so once you get used to it, you can start Compute Engine and launch the flask web application in minutes! If you like, try it: relaxed:
Recommended Posts