【初心者向け】さくらVPSで ubuntu – docker – apache2 – wsgi – flask 環境を作るまで、一通りやってみた。
Hi, I’m dog-ears.
Recently I started studying python, so I first summarized from environment building.
As it is the title, from the point of contracting a further VPS,
Until you publish the Flask (Python framework) test page on the web.
It may be more than building a server environment rather than a Python tutorial.
OK, let’s get started.
Index.
(1) OS installation
(2) Installation of vim
(3) SSH setting
(4) iptables
(5) SSH connection setting using public key encryption
(6) Installation of Docker
(7) Install Apache
(8) Installation of Python 3.6
(9) Installation & setting of mod_wsgi, setting of Flask
(10) Installing & setting Flask
(11) Implementation of SSL
(1) OS installation
Install from Sakura’s VPS management screen
Installation format: Standard OS
OS: Ubuntu 16.04 amd64
Startup script: [public] Ubuntu_apt-get_update_upgrade
When installation is over, it will be “in operation"
Upgrading may take time.
You can check the status from the management screen and the console’s VNC console.
(2) Installation of vim
sudo apt install vim
(3) SSH setting
dpkg -l | grep openssh-server
Confirm that openssh-server has been installed.
If it is not installed,install it
sudo apt install openssh-server
sudo vim /etc/ssh/sshd_config
- Change Port to an arbitrary number
- PermitRootLogin changed to no
sudo systemctl restart sshd
We also change the settings of services (even though we did not do it, it worked ….)
sudo vim /etc/services
- Change the SSH port number
At this point, due to iptables, I can not enter in the new port.
(4) iptables
How to set iptables (*japanese)
https://help.sakura.ad.jp/hc/ja/articles/206208121
Easy commentary on firewall iptables – even beginners can understand! Web server operation course by VPS (4) (*japanese)
https://knowledge.sakura.ad.jp/4048/
sudo vim /etc/iptables/iptables.rules
Modified based on reference site
SSH and HTTP (80), HTTPS (443) opened.
Restart iptables
I did not understand how to do it, so I restarted each server.
(5) SSH connection setting using public key encryption
SSH connection with public key authentication – How to use Tera Term
https://webkaru.net/linux/tera-term-ssh-login-public-key/
How to set WinSCP private key
https://synclogue-navi.com/winscp-privatekey
In Tera Term, menu – SSH key generation
- Generated by default setting
Passphrase is OK even in the blank
Save the private key and the public key locally.
After connecting to the server in Tera Term, drag and drop the public key
Enter “~ /" and “SCP"
mkdir .ssh chmod 700 .ssh mv sakura2.pub .ssh/authorized_keys
* When logging in from another PC, create a public key / secret key on another PC,
You can add the contents of the public key as a new line to the already existing authorized_keys.
Restart SSh
sudo systemctl restart sshd
Log out here and check if SSH login is possible.
Fixed the following files so that you can not log in when you can check
sudo vim /etc/ssh/sshd_config
- PasswordAuthentication no
Restart SSh
sudo systemctl restart sshd
Confirm that you can not log in with your password.
It also connects with WinScp
With a new connection, empty the password field,
Set up the secret key with setting – SSH – authentication.
Convert to ppk format?
As you are asked, choose yes,
Save in ppk format.
If you select converted ppk format OK
(6) Installation of Docker
Get Docker CE for Ubuntu (Official)
https://docs.docker.com/install/linux/docker-ce/ubuntu/
Preparation for installation
sudo apt-get update sudo apt-get install apt-transport-https ca-certificates curl software-properties-common curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add - sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
Execute installation
sudo apt-get update sudo apt-get install docker-ce
Post-installation work
Create Docker group and add ubuntu user to Docker group
sudo groupadd docker sudo usermod -aG docker $USER
After finishing, log out and log in again.
Now, ubuntu users can now run docker.
Make Docker launch at startup
sudo systemctl enable docker
— Memo —
Container status check
docker images docker ps -a
Creation / activation of containers
docker pull ubuntu:16.04 docker run -it -d --name ubuntu1604 -p 80:80 -p 443:443 --restart=always -v /var/www:/var/www ubuntu:16.04
* We name the container ubuntu 1604.
* Restart will be automatically restarted when restarting the host.
— Memo —
Container stopped
docker stop ubuntu1604
Launch container
docker start ubuntu1604
Delete all containers not activated
sudo docker rm $(sudo docker ps -a -q)
Launch bash in container
docker exec -it ubuntu1604 /bin/bash
After that, working inside the container.
Default, since it is root, please omit the command sudo when executing as it is.
apt update it
sudo apt update sudo apt upgrade -y
Let’s put in vim at the same time
sudo apt install vim
(7) Install Apache
sudo apt install apache2 apache2-dev
* apache2-dev seems necessary for the subsequent mod_wsgi installation.
Confirmation of service.
service --status-all
Apache 2 is installed, but it was in a state of not running.
Start apache2
sudo service apache2 start
You can now see the Apache default page by direct ip.
In the meantime, set up the domain so that it can be seen in the subdomain.
Register ip in the A record on the management screen of the contracted domain company OK.
(8) Installation of Python 3.6
First, install add-apt-repository
Ubuntu 14.04 said that there is no add-apt-repository (japanese)
https://loumo.jp/wp/archive/20150626000042/
sudo apt-get install apt-file sudo apt-file update sudo apt-file search add-apt-repository sudo apt-get install software-properties-common
Next, install python 3.6 and pip
Upgrade Python version from 2.7 to 3.6 with Ubuntu 16.04 (japanese)
https://tetechi.com/python3-6/
sudo add-apt-repository ppa:jonathonf/python-3.6 sudo apt-get update sudo apt-get install python3.6 python3.6-dev curl -fsSL -o get-pip.py https://bootstrap.pypa.io/get-pip.py sudo python3.6 get-pip.py rm get-pip.py
Confirm that 3.6.5 was entered with python 3.6-V
Change default version to 3.6
ln -s /usr/bin/python3.6 /usr/bin/python
With python – V,
It was displayed as Python 3.6.5.
(9) Installation & setting of mod_wsgi, setting of Flask
Create web applications with Python 3 using Flask in Ubuntu’s Apache (japanese)
http://blog.akashisn.info/entry/%3Fp%3D258
Draw hello world on mod_wsgi (japanese)
https://qiita.com/shigechioyo/items/2b25f60918be6b81581a
Display Japanese in python3 / mod_wsgi (japanese)
http://www.ohneta.net/wiki/index.php?python3/mod_wsgi%E3%81%A7%E6%97%A5%E6%9C%AC%E8%AA%9E%E8%A1%A8%E7%A4%BA
[Python] Move Python 3.6 with Apache using mod_wsgi (CentOS 6 series) (japanese)
https://www.yoheim.net/blog.php?q=20170206
Python: About mod_wsgi’s built-in mode and daemon mode (japanese)
http://blog.amedama.jp/entry/2015/08/16/220628
Points to note when using Python 3.4 + mod_wsgi + mysql5 with Ubuntu (japanese)
https://ur.edu-connect.net/archives/28888
AssertionError using Apache2 and libapache2-mod-wsgi-py3 on Ubuntu 14.04 (Python 3.4)
https://askubuntu.com/questions/569550/assertionerror-using-apache2-and-libapache2-mod-wsgi-py3-on-ubuntu-14-04-python
As a result of trying various reference pages,
I proceeded in the following way.
Installation & loading of mod_wsgi
sudo pip install mod_wsgi
There seems to be various ways such as installing with apt,
Installation on pip seems to be safe.
Search installed location
find . -name mod_wsgi-py36.cpython-36m-x86_64-linux-gnu.so
As a result,
/usr/local/lib/python3.6/dist-packages/mod_wsgi/server/mod_wsgi-py36.cpython-36m-x86_64-linux-gnu.so
It seems that it was installed.
Let apache recognize this file.
sudo vim /etc/apache2/mods-available/wsgi.load
Description below. After wsgi_module, let’s write the location you searched for earlier.
LoadModule wsgi_module /usr/local/lib/python3.6/dist-packages/mod_wsgi/server/mod_wsgi-py36.cpython-36m-x86_64-linux-gnu.so
Enable wsgi
sudo a2enmod wsgi
apache2 restart
sudo service apache2 restart
When apache 2 was restarted,
AH00558: apache2: Could not reliably determine the server’s fully qualified domain name
I got an error with.
Resolve the apache2 AH00558 error in ubuntu. (japanese)
http://mk-55.hatenablog.com/entry/2014/07/07/004510
sudo echo ServerName $HOSTNAME > /etc/apache2/conf-available/fqdn.conf sudo a2enconf fqdn sudo service apache2 restart
This no longer causes an error.
Next, change apache configuration setting.
(I will take a backup once.)
sudo cp /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-available/000-default.conf.bk sudo vim /etc/apache2/sites-available/000-default.conf
<VirtualHost *:80> WSGIDaemonProcess myapp-process user=www-data group=www-data threads=5 WSGIScriptAlias / /var/www/html/app.wsgi ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined <Directory /var/www/html> WSGIProcessGroup myapp-process WSGIApplicationGroup %{GLOBAL} Order deny,allow Allow from all </Directory> </VirtualHost>
About Python: mod_wsgi’s built-in mode and daemon mode (japanese)
http://blog.amedama.jp/entry/2015/08/16/220628
Because mod_wsgi seems to recommend daemon mode,
Launch the process with the name myapp-process.
In WSGIScriptAlias, I specify a wsgi file to call.
apache restart
sudo service apache2 restart
Create a wsgi file to be invoked
vim /var/www/html/app.wsgi
Description
def application(environ, start_response): status = '200 OK' output = b'Hello World!' response_headers = [('Content-type', 'text/plain'), ('Content-Length', str(len(output)))] start_response(status, response_headers) return [output]
When opening the ip address or the set domain in the browser,
I could confirm Hello World.
(10) Installing & setting Flask
Installing Flask
sudo pip install Flask
Installation of wsgi & py file
vim /var/www/html/app.wsgi
Change description as follows
import os,sys sys.path.insert(0, os.path.abspath(os.path.dirname(__file__))) from main import app as application
Just import app from main.py as application.
vim /var/www/html/main.py
Described below
from flask import Flask app = Flask(__name__) @app.route("/") def index(): return "Flask-index OK!"
I opened it in the browser and confirmed the display.
(11) Implementation of SSL
Let’s try SSL compliance with Let’s Encrypt.
SSL with Apache 2.4 on Ubuntu 16.04 (japanese)
https://qiita.com/tontan9616/items/bd8b2f1f360f26c7bb46
Ubuntu on Sakura’s VPS uses Let’s Encrypt’s SSL certificate and moves to Https (japanese)
https://loumo.jp/wp/archive/20171021120015/
How to automatically update Let’s Encrypt with Sakura’s VPS (Cent OS 6.8) (japanese)
https://qiita.com/childsview/items/e4bff3b32b8304553980
Surprisingly easy! How to support HTTPS Flask [Let’s encrypt] (japanese)
https://blog.capilano-fw.com/?p=374
Install certbot command
sudo apt-get update sudo apt-get install software-properties-common sudo add-apt-repository ppa:certbot/certbot sudo apt-get update sudo apt-get install python-certbot-apache
Change main.py
vim /var/www/html/main.py
from flask import Flask, render_template app = Flask(__name__) @app.route("/") def index(): return "Flask-index OK!" @app.route('/.well-known/acme-challenge/<filename>') def well_known(filename): return render_template('.well-known/acme-challenge/'+ filename)
Create template folder
mkdir -p /var/www/html/templates
sudo certbot certonly --webroot -w /var/www/html/templates/ -d example.com -m info@example.com
Replace example.com as appropriate.
Let’s get the acquisition of the authentication key.
Acquisition of authentication key
sudo certbot certonly --webroot -w /var/www/html/templates/ -d example.com -m info@example.com
· · · However error. “I went to look for certification, but it was notFound."
Just in case, apache2 restart
sudo service apache2 restart
When I got the authentication key again, I succeeded successfully.
/etc/letsencrypt/live/example.com/fullchain.pem /etc/letsencrypt/live/example.com/privkey.pem
It was preserved.
Finally, change the setting of apache2.
First, enable the ssl and rewrite modules.
sudo a2enmod ssl sudo a2enmod rewrite
a2enmod rewrite
Confirm that the module has been loaded.
apache config setting
sudo vim /etc/apache2/sites-available/000-default.conf
<VirtualHost *:80> ServerName example.com RewriteEngine on RewriteCond %{HTTP_HOST} ^example\.com RewriteRule ^/(.*)$ https://example\.com/$1 [R=301,L] </VirtualHost> <VirtualHost *:443> # SSL SSLCertificateFile /etc/letsencrypt/live/example.com/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem ServerName example.com # WSGI WSGIDaemonProcess myapp-process user=www-data group=www-data threads=5 WSGIScriptAlias / /var/www/html/app.wsgi <Directory /var/www/html> WSGIProcessGroup myapp-process WSGIApplicationGroup %{GLOBAL} Order deny,allow Allow from all </Directory> </VirtualHost>
After saving, restart apache2.
sudo service apache2 restart
When opening a domain in the browser,
It was automatically redirected to https and displayed.
That’s it, until we released the Flask application on Sakura VPS.
I will study Python applications in this environment from the next time onwards.
Discussion
New Comments
No comments yet. Be the first one!