☆☆ 新着記事 ☆☆

2018年12月29日土曜日

[最終版] mod_wsgi と 複数ドメインを管理するvirtual host でLet's Encryptをインストールする(SSL対応)

mod_wsgi経由でDjangoやFlaskを使いつつ、Virtual Hostで複数のサブ・ドメインを1台のサーバで動かしたい。(勿論、wwwホスト名 あり・なしにも対応。) 

しかも、各ドメインは、SSLにも対応させる。
結構、難しくないですか? Virtual Hostの書き方を把握するまで、凄く時間がかかったので、まとめておきます。
--------------------------------------------------------------------------------

***** Important Notice *****
前半の記述は、失敗版だと判明しました。 この記述だと、一番最初に読み込んだ
    flask appが保持されて、別のflask appに切り替わりません。 
     この問題には、stackoverflowに、mod_wsgiの開発者であるGraham Dumpleton さん
           自身が回答されていましたので、そのガイドに基づいて、再度、設定を修正しています。
           このpostの後半に書きました。 最初の部分は、読み飛ばしてください。
 

mod_wsgiを利用した場合の基本的なVirtual Hostの書き方は、
【 複数のサブドメインを管理しているサーバで、wsgiを使う時のVirtual Hostの書き方  】
に、まとめました。

この書き方で、’wwwあり・なし’、’複数のサブドメイン’に対応することができます。
(あわせて、mod_wsgiのスクリプトがあるディレクトリ配下でも、staticなファイルは直接、ブラウザから呼び出せるようにしています。)

このポストでは、これをSSLに対応させる(Let's Encrypt) 時のVirtual Hostの書き方と注意点を書いておきます。

◆環境
CentOS 7 + Apache 2.4 + mod_wsgi 4.6.5 + Flask
で、挙動確認しています。

◆対象ドメイン
(Freenomで12か月、無料で取得したもの。DNSもすべてに同じIP Addressを指定しています。)
- mossymob.tk
- www.mossymob.tk
- taylor.mossymob.tk


***********(前半 失敗の部)***********

◆結論
Virtual Hostの記載:
conf.d ディレクトリの配下に 'vhosts_www.conf' を作り、記述しています。

[root@cnewgwb6 conf.d]# pwd
/etc/httpd/conf.d
[root@cnewgwb6 conf.d]# cat vhosts_www.conf


LoadModule wsgi_module /usr/lib64/httpd/modules/mod_wsgi.so

WSGIApplicationGroup %{GLOBAL}
WSGIDaemonProcess www user=apache group=apache maximum-requests=10000 <- ①
WSGIProcessGroup www

 <VirtualHost *:80>
   ServerName www.mossymob.tk
   DocumentRoot /var/www/html
   Alias /posts  /var/www/html/posts <- ②
   WSGIScriptAlias / /var/www/html/myapp.wsgi
   <Directory "/var/www/html/">
     Options Includes ExecCGI FollowSymLinks
   </Directory>
 </VirtualHost>
<VirtualHost *:80>
   ServerName mossymob.tk <- ③
   DocumentRoot /var/www/html
   Alias /posts  /var/www/html/posts
   WSGIScriptAlias / /var/www/html/myapp.wsgi
   <Directory "/var/www/html/">
     Options Includes ExecCGI FollowSymLinks
   </Directory>
 </VirtualHost>

<VirtualHost *:80>
   ServerName taylor.mossymob.tk
   DocumentRoot /var/taylor/html
   Alias /posts  /var/taylor/html/posts
   WSGIScriptAlias / /var/taylor/html/myapp.wsgi
   <Directory "/var/uslife/html/">
     Options Includes ExecCGI FollowSymLinks
     Require all granted <- ④
  </Directory>
 </VirtualHost>
 

注意点)

①デーモン・モードについて
明示的にdeamon modeを指定してあげないと"ValueError: Unable to set value to path!" とエラーになります。 そこで、個別の<VirtualHost></VirtualHost>の中に、それぞれ記述しましたが、 "Name duplicates previous WSGI daemon definition.” というエラーになりました。 

記述は、こんな感じ。
LoadModule wsgi_module /usr/lib64/httpd/modules/mod_wsgi.so
 <VirtualHost *:80>
   ServerName mossymob.tk
   WSGIDaemonProcess www user=apache group=apache maximum-requests=10000
   DocumentRoot /var/www/html
   WSGIScriptAlias / /var/www/html/myapp.wsgi process-group=www
   <Directory "/var/www/html/">
     Options Includes ExecCGI FollowSymLinks
   </Directory>
 </VirtualHost>


結局、個別の<VirtualHost>コンテナーの外に記述することで、このName duplicates errorを回避しました。

*maximm requests:
Use of maximum-requests is discouraged for production sites unless you really have a crippling memory leak you can't fix straight away. – Graham Dumpleton Jul 6 '11 at 5:18


②mod_wsgiとstatic file

必須ではないかもしれませんが、htmlなどの静的なファイルは、将来、mod_wsgiを介さないでブラウザに表示したいので、その為の設定です。 wsgiスクリプトが設置されたディレクトリにpostsというディレクトリを作り、その配下のファイルは、ブラウザから直接、アクセスできるようにしました。

③ wwwサブドメイン名なしのURLについて

Server Aliasを当初使っていましたが、この設定があるとLet's Encriptは上手く機能しないようです。 冗長ですが個別に<VirtualHost>の記述をすることにしました。

④Require all granted
   mossymob.tk や www.mossymob.tk の<VirtualHost>の<Directory>コンテナーの中には記述不要ですが、別サブ・ドメインの時には、この記述が必須になります。 wwwは、mod_wsgiの読み込みのデフォルト・ルートになっているからでしょうか? 理由は良く分かりません。

ここまできたら、Let's Encrypt で、certbotを実行します。
コマンドは、ルート・ディレクトリで以下の実行をしました。

# certbot --apache -d mossymob.tk

-d のオプションでドメイン名を指定しなければ、一括してSSL対応になるようですが、一つずつ対応させた方が、どのドメインに問題があるか把握するのが容易です。

certbotが実行される毎に、’vhosts_www-le-ssl.conf' (自分が作成したvirtual host記述ファイル名+le-ssl.conf)が作成されます。 (後から実行したドメインの記述は、このファイル内に追加されます。

地道に全てのドメインに対して実行した後の’vhosts_www-le-ssl.conf'の内容が以下になります。
[root@cnewgwb6 conf.d]# cat vhosts_www-le-ssl.conf


<IfModule mod_ssl.c>
<VirtualHost *:443>
   ServerName mossymob.tk
   DocumentRoot /var/www/html
   Alias /posts  /var/www/html/posts
   WSGIScriptAlias / /var/www/html/myapp.wsgi
   <Directory "/var/www/html/">
     Options Includes ExecCGI FollowSymLinks
   </Directory>
   SSLCertificateFile /etc/letsencrypt/live/mossymob.tk-0001/cert.pem
   SSLCertificateKeyFile /etc/letsencrypt/live/mossymob.tk-0001/privkey.pem
    Include /etc/letsencrypt/options-ssl-apache.conf
    SSLCertificateChainFile /etc/letsencrypt/live/mossymob.tk-0001/chain.pem
</VirtualHost>
</IfModule>

<IfModule mod_ssl.c>
 <VirtualHost *:443>
   ServerName www.mossymob.tk
   DocumentRoot /var/www/html
   Alias /posts  /var/www/html/posts
   WSGIScriptAlias / /var/www/html/myapp.wsgi
   <Directory "/var/www/html/">
     Options Includes ExecCGI FollowSymLinks
   </Directory>
  SSLCertificateFile /etc/letsencrypt/live/www.mossymob.tk/cert.pem
  SSLCertificateKeyFile /etc/letsencrypt/live/www.mossymob.tk/privkey.pem
  Include /etc/letsencrypt/options-ssl-apache.conf
  SSLCertificateChainFile /etc/letsencrypt/live/www.mossymob.tk/chain.pem
</VirtualHost>
</IfModule>

<IfModule mod_ssl.c>
<VirtualHost *:443>
   ServerName taylor.mossymob.tk
   DocumentRoot /var/taylor/html
   Alias /posts  /var/taylor/html/posts
   WSGIScriptAlias / /var/taylor/html/myapp.wsgi
   <Directory "/var/taylor/html/">
     AllowOverride None <- ②
     Options Includes ExecCGI FollowSymLinks
     Require all granted <- ①
   </Directory>
   Include /etc/letsencrypt/options-ssl-apache.conf
   SSLCertificateFile /etc/letsencrypt/live/uslife.mossymob.tk/cert.pem
   SSLCertificateKeyFile /etc/letsencrypt/live/uslife.mossymob.tk/privkey.pem
   SSLCertificateChainFile /etc/letsencrypt/live/uslife.mossymob.tk/chain.pem
   </VirtualHost>
</IfModule>


注意点)

① <Directory "/var/taylor/html/"> の記述

基本的に、Let's Encryptのcerbotが自動で作成するconfファイルは、自分で記述したvirtual hostの記述内容をコピーしてきて、その内容にsslの対応をさせる、というものだと思います。
でも、確実にコピーがされるか、というと疑問です。 自分の場合、赤字のRequire all grantedがコピーされていませんでした。 それが certbot の正しい挙動なのか分かりませんが、再度、自分で確認した方が良いでしょう。

 ② AllowOverride None 
この記述は、httpのオリジナルの<Virtual Host>内には記述していません。 しかし、SSLの時には、この記述がないと、うまくwsgi scriptが機能しません。 理由の把握までは出来ていません。


これが最終版。





***********(前半 失敗の部 終了 & 正答版開始)***********

Let's EncrytのcertbotでSSLを設定しようとすると、 "Name duplicates previous WSGI daemon definition.”というエラーが表示される件について、mod_wsgiの開発者 Graham Dumpleton さんは、

As the error says, you cannot use the same name for a WSGIDaemonProcess definition more than once. They have to be unique for the whole Apache instance.
If you have both 80 and 443 instances of the VirtualHost for same ServerName, you shouldn't create a separate WSGIDaemonProcess in the 443 instance. Define it in the 80 instance and reference by name from the 443 instance. That way you share the same daemon process group between 80 and 443 instances of the VirtualHost for the same ServerName.


要は、certbotを走らせると <VirtualHost *:80> をcopyする形で、<VirtualHost *:443>用の新しいファイルが作られますが、すると、その記述の中に、再び、DaemonProcessの同じ名前が使われてしまうので、こんな感じで書いて、

WSGIApplicationGroup %{GLOBAL}
WSGIRestrictEmbedded On

<VirtualHost *:80>
ServerName example.com
WSGIDaemonProcess myprocess threads=10 home=/home/ubuntu/myapp
WSGIProcessGroup myprocess
...
</VirtualHost>

<VirtualHost *:443>
ServerName example.com
WSGIProcessGroup myprocess
...               ← WSGIDaemonProcess は記述しない、
</VirtualHost>

と、回答しています。

なので、ホスト名ごとに<VirtualHost>を記述したconfファイルを以下のように作ることにします。

file名:mossymob.tk.conf

LoadModule wsgi_module /usr/lib64/httpd/modules/mod_wsgi.so

WSGIApplicationGroup %{GLOBAL}
WSGIRestrictEmbedded On

  <VirtualHost *:80>
    ServerName mossymob.tk
    WSGIDaemonProcess bear user=apache group=apache
    WSGIProcessGroup bear
    DocumentRoot /var/www/html
    Alias /posts  /var/www/html/posts
    WSGIScriptAlias / /var/www/html/myapp.wsgi
    <Directory "/var/www/html/">
      Options Includes ExecCGI FollowSymLinks
    </Directory>
  </VirtualHost>

  <VirtualHost *:443>
    ServerName mossymob.tk

    WSGIProcessGroup bear
    DocumentRoot /var/www/html
    Alias /posts  /var/www/html/posts
    WSGIScriptAlias / /var/www/html/myapp.wsgi
    <Directory "/var/www/html/">
      Options Includes ExecCGI FollowSymLinks
    </Directory>
</VirtualHost>

そして、
# certbot --apache -d mossymob.tk

を実行。

<VirtualHost *:443>
    ServerName mossymob.tk
    WSGIProcessGroup bear
    DocumentRoot /var/www/html
    Alias /posts  /var/www/html/posts
    WSGIScriptAlias / /var/www/html/myapp.wsgi
    <Directory "/var/www/html/">
      Options Includes ExecCGI FollowSymLinks
    </Directory>
  SSLCertificateFile /etc/letsencrypt/live/mossymob.tk-0001/cert.pem
  SSLCertificateKeyFile /etc/letsencrypt/live/mossymob.tk-0001/privkey.pem
  Include /etc/letsencrypt/options-ssl-apache.conf
  SSLCertificateChainFile /etc/letsencrypt/live/mossymob.tk-0001/chain.pem
  </VirtualHost>


* 赤字部分がLet's Encryptのcertbotにより自動で追加された部分。

この作業をSSL化したい全てのサブ・ドメインに対して実行します。

これで、本当に想定した通りの挙動になります。

confファイルを変更した後は、systemctl reload httpdの実行を忘れてはいけません。

以上です。

結構、時間がかかりましたが、これで思い通りの挙動をするようになりました。
皆様にも参考になれば。


2018年12月28日金曜日

複数のサブドメインを管理しているサーバで、wsgiを使う時のVirtual Hostの書き方

Pythonのフレーム・ワークであるDjangoやFlaskを動かすときには、wsgiを使うことが推奨されています。(各アプリで、同時処理を可能にするため。)

ところで、このwsgi (apacheを使っているので、mod_wsgi) を、複数のサブドメインを管理しているサーバーで使う時には、Virtual Hostの書き方に工夫が必要なようです。ネットで検索しても、ピタッとくる回答がないので、一つずつ書き方を検証していきます。

検証環境:Apache 2.4  + wsgi



(Testの構成)
* ドメイン・サブドメイン
 1)           mossymob.tk
   2) www.mossymob.tk
   3) uslife.mossymob.tk

(Global IP アドレス 1つで運用しまています。外部DNSは設定済み、とします。)



1.基本: mossymob.tk と www.mossymob.tk をaliasで管理。

mossymob.tk と www.mossymob.tkを動かすvirtualhost.confの記述。

[root@cnewgwb6 conf.d]# pwd
/etc/httpd/conf.d
[root@cnewgwb6 conf.d]# ls -a
.   autoindex.conf  README    userdir.conf      welcome.conf
..  manual.conf     ssl.conf  virtualhost.conf

LoadModule wsgi_module /usr/lib64/httpd/modules/mod_wsgi.so

<VirtualHost *:80>
  ServerName mossymob.tk
  ServerAlias www.mossymob.tk
  DocumentRoot /var/www/html
  WSGIScriptAlias / /var/www/html/myapp.wsgi
  <Directory "/var/www/html/">
    Options Includes ExecCGI FollowSymLinks
  </Directory>
</VirtualHost>

wwwつきも、mossymob.tk と同じ Document Root 、同じDirectory コンテナの内容なので、
結局、1つだけのドメインを管理しているのと同じですから、うまく機能します。

WSGIScriptには、以下の内容が書いてあります。
# coding: utf-8
import sys
sys.path.insert(0, '/var/www/html')
from app import app as application

**この段階で、wsgiを使わないシンプルな、staticのhtmlファイルが、wsgiファイルが設定されているフォルダに同居していると、機能するか検証します。

[root@cnewgwb6 html]# pwd
/var/www/html

[root@cnewgwb6 html]# ls -l
-rwxr--r-x 1 root root 173 Dec 28 13:22 app.py
-rwxr-xr-x 1 root root 206 Dec 28 17:37 hello.html
-rw-r--r-- 1 root root 103 Dec 28 12:53 myapp.wsgi

この場合、app.pyは動くが、hello.htmlはHTTP 404エラーになる。


では、htmlの配下に、更に、blog ディレクトリをつくって、そこに格納したら動くか?

[root@cnewgwb6 blog]# pwd
/var/www/html/blog
[root@cnewgwb6 blog]# ll
-rw-r--r-- 1 root root 206 Dec 28 17:53 hello.html

答えは
HTTP 404エラー

こういった場合、

<VirtualHost *:80>
   ServerName mossymob.tk
   ServerAlias www.mossymob.tk
   DocumentRoot /var/www/html
   Alias /blog  /var/www/html/blog
   WSGIScriptAlias / /var/www/html/myapp.wsgi
 (以下、省略)

と、赤の網掛けをしたAlias を記述することで、

wsgiを経由しないで、直接アクセスしたいstaticなファイルを指定

できるようです。




参考)mod_wsgi : Quick Configuration Guide
https://modwsgi.readthedocs.io/en/develop/user-guides/quick-configuration-guide.html

Mounting At Root Of Site
If instead you want to mount a WSGI application at the root of a site, simply list ‘/’ as the mount point when configuring the WSGIScriptAlias directive:

WSGIScriptAlias / /usr/local/www/wsgi-scripts/myapp.wsgi

Do note however that doing so will mean that any static files contained in the DocumentRoot will be hidden and requests against URLs pertaining to the static files will instead be processed by the WSGI application.
In this situation it becomes necessary to remap using the Alias directive, any URLs for static files to the directory containing them:

Alias /robots.txt /usr/local/www/documents/robots.txt
Alias /favicon.ico /usr/local/www/documents/favicon.ico
Alias /media/ /usr/local/www/documents/media/


2.2つ目のサブドメイン(uslife.mossymob.tk)をVirtual Hostに追加

さて、本題の、別のサブドメインのwsgi経由のflaskのアプリケーションや静的ファイルを、virtual hostで、どう管理するか。

上記のVirtual Hostの記述に、単純に以下のVirtualHostを追加すると、エラーになってhttpdが起動できなくなる。

<VirtualHost *:80>
     ServerName uslife.mossymob.tk
     DirectoryIndex index.html
     AddDefaultCharset UTF-8
     DocumentRoot /var/uslife/html/
     <Directory "/var/uslife/html/">
      AllowOverride All
      Options FollowSymLinks -Indexes
     </Directory>
 </VirtualHost>

[root@cnewgwb6 conf.d]# systemctl reload httpd
Job for httpd.service failed because the control process exited with error code.

-- A session with the ID 9 has been terminated.
Dec 28 16:44:39 cnewgwb6 polkitd[619]: Registered Authentication Agent for unix-process:13891:2146407 (system bus name :1.87
Dec 28 16:44:39 cnewgwb6 httpd[13898]: httpd: Syntax error on line 360 of /etc/httpd/conf/httpd.conf: Syntax error on line 1
Dec 28 16:44:39 cnewgwb6 systemd[1]: httpd.service: control process exited, code=exited status=1
Dec 28 16:44:39 cnewgwb6 systemd[1]: Reload failed for The Apache HTTP Server.

というエラー。

こういう場合は、デーモン・プロセスを指定するそうなので、下記がその内容。


LoadModule wsgi_module /usr/lib64/httpd/modules/mod_wsgi.so
 <VirtualHost *:80>
   ServerName mossymob.tk
   ServerAlias www.mossymob.tk
   WSGIDaemonProcess www user=apache group=apache

   DocumentRoot /var/www/html
   Alias /blog  /var/www/html/blog
   WSGIScriptAlias / /var/www/html/myapp.wsgi process-group=www
   <Directory "/var/www/html/">
     Options Includes ExecCGI FollowSymLinks
   </Directory>
 </VirtualHost>

  <VirtualHost *:80>
   ServerName uslife.mossymob.tk
   WSGIDaemonProcess uslife user=apache group=apache

   DocumentRoot /var/uslife/html
   Alias /blog  /var/uslife/html/blog
   WSGIScriptAlias / /var/uslife/html/myapp.wsgi process-group=uslife
   <Directory "/var/uslife/html/">
     Options Includes ExecCGI FollowSymLinks
   Require all granted   ## 注意
   </Directory>
 </VirtualHost>
 

 ##注意)
 'Require all granted’ の記述がないと、以下のようなエラーになります
 [authz_core:error] [pid 23111] [client 175.132.xxxx.xxxx] AHxxxx: client denied by server configuration: /var/uslife/html/blog/hello.html
 flask.appも、blog配下のhtmlも読み込めません。 この記述を付け足す事で、どちらも表示できるように  なります。
  全く同一構成の、mossymob.tk / www.mossymob.tk のVirtual Hostの<Directory>コンテナーの中には、この記述は不要です。 (というか、なくても問題なく表示されている。)

 どうしてそうなるのか、今のところ、自分には理由は分かりません。
 (疲れたので、調べてもいません。)

 無事に、別のサブドメインの内容が、Virtual Hostの記述で表示できるようになったので、
 良し、とします。

 
 
 
おしまいです。

2018年12月27日木曜日

【サブ・ドメインを使う時の基本設定】 Apache の Virtual Host の基本的な2つの書き方

◇記載内容

この投稿では、Apache2.4 のVirtual Hostを使って、1つのIPアドレスで、複数のサブ・ドメインを使う時の2つの記述方法と注意点を記載しています。

特に、wwwつき、なしを管理する場合は、有効です。 (この投稿では書きませんが、DNSには、全てのサブドメインに対して、使用するIPアドレスをAレコードに登録するなどの作業を忘れずにしてくださいね。)


*自分が使っているDNS管理会社の管理画面です。

個別のhtmlファイルをそれぞれのサブドメインに設置するとか、WordPressのブログに別のサブドメイン名を使いたいといったようば場合は、この設定で充分です。
但し、何等かのアプリをプログラムで作成して、Frameworkを使ってルーティングさせたい場合の設定は、次回以降の投稿を参考にしてください。



◇Virtual Hostとは

 1台のサーバーにインストールしたApacheを使って、複数のドメインでサービスを行うための仕組み。

Apache 2.4 のconf 設定ファイルは

/etc/httpd/conf/ httpd.conf  

という、最初に読み込まれるファイルあり、

/etc/httpd/conf.d  や
/etc/httpd/conf.modules.d   等の

それぞれのディレクトリに、個別のサブ・ドメインに対応したバーチャルホストの設定が書かれています。

[root@  /]# ls -a etc/httpd/
.  ..  conf  conf.d  conf.modules.d  logs  modules  run

Apache 2.4 の設定ファイルは /etc/httpd/conf/httpd.conf というファイルが大元となっており、個別のモジュールなどの設定は /etc/httpd/conf.d /etc/httpd/conf.modules.d ディレクトリに設定が保存されています。 httpd.conf から、 conf/conf.d や conf/conf.modules.d フォルダの設定を Include するようになっています。


(参考:conf.modules.d ディレクトリやconf.d ディレクトリの全てを読み込めと書いてあるのが確認できます。)
[root@  /]# ls -a etc/httpd/
  .  ..  conf  conf.d  conf.modules.d  logs  modules  run
[root@ conf]# pwd
 /etc/httpd/conf

[root@ conf]# vi httpd.conf
Include conf.modules.d/*.conf
IncludeOptional conf.d/*.conf  

従って、conf.d ディレクトリの配下に、任意の名前のconf ファイルを作って管理することが可能。

勿論、httpdに直接、記載することも可能ですが、 多くのサブドメイン(ホスト名)を利用する場合などは、別ファイルにした方が分かり易いと思います。 
(自分は、conf.d/ ディレクトリの配下に、サブホスト名をファイル名につけた.conf ファイル を作成して管理します。)


  (設定)
1.  大元のhttpd.confに直接編集する必須の記述

Virtual Hostを使用することの宣言を書きます。作業は、デフォルトの記述でコメントアウトになっているホスト名を記述している箇所が、きちんとコメントアウトされているか確認。
次に、バーチャル・ホストを使うことを宣言する1行を書きます。

(デフォルトのファイル保管場所)
/etc/httpd/conf/httpd.conf

1) コメントアウトの確認
  (修正前)
      ServerName www.example.com:80
   ↑ Defaultではコメントアウトになっているので、特別に設定を変えていなければ修正不要。

    (修正後:コメントアウト)
    #ServerName www.example.com:80 

2) 名前ベースの VirtualHost の待受けをすることを宣言)
  記載する場所はどこでも可だが、とりあえず 'Listen 80'の下に書く。
  NameVirtualHost *:80

2. 個別の.confファイルの記述
 
次に、個別のバーチャルホストの設定をconfファイルに記述します。

/etc/httpd/conf.d/virtual.confの作成・編集
(virtual.conf のvirtualは任意につけてください。以下、このconfファイルに記載する内容です。)

 方法1) ServerAliasを使う方法

Virtual Hostには、DocumentRootとServerNameが必須の記載事項だが、この方法だと、何度も同じような記載をしてくても良いので簡易。 ただし、Server Aliasのサブホスト(ホスト名)のDocument Rootは、オリジナルのDocument Rootと一緒してしまう擬似的な方法。

記載している内容は、
www.mossymob.tk のアクセスは、mossymob.tk と同じ(alias)
と指定しているだけ。

この為、アップロードするコンテンツを、サブ・ドメイン(ホスト名)毎に管理したい場合は、方法2の方が便利。 又、Let's Encryptを使ってSSLに対応する場合、このメソッドは機能しない。

(実際の virtual.confの記入例)
[root@ip2h3wsy httpd]# ls -a
.  ..  conf  conf.d  conf.modules.d  logs  modules  run
[root@ip2h3wsy conf.d]# touch virtual.conf
[root@ip2h3wsy conf.d]# vi virtual.conf

< VirtualHost *:80>
 ServerAdmin root@mossymob.tk
 DocumentRoot /var/www/html
 ServerName mossymob.tk
 ServerAlias www.mossymob.tk  <- wwwはServer Aliasで対応できる。
 ServerAlias www.mossymob.net <- 複数のドメインでも、Server Aliasで対応できる。

CustomLog /var/www/html/access.log common <- ログは検証時のみ。必要なら。
ErrorLog /var/www/html/error.log <- apacheのパフォーマンスが顕著に悪くなる。
< /VirtualHost>

方法2 順番に個別に記載する

(Virtual Hostを複数記入する場合の例)
  #1つめのサイト
 <VirtualHost *:80>
    ServerName mossymob.tk
    DirectoryIndex index.html index.php
    AddDefaultCharset UTF-8
    DocumentRoot /var/www/html/
    <Directory "/var/www/html/">
     AllowOverride All
     Options FollowSymLinks -Indexes
    </Directory>
 </VirtualHost>

  #2つ目のサイト
 <VirtualHost *:80>
    ServerName www.mossymob.tk
    DirectoryIndex index.html index.php
    AddDefaultCharset UTF-8
    DocumentRoot /var/www/html/
    <Directory "/var/www/html/">
     AllowOverride All
     Options FollowSymLinks -Indexes
    </Directory>
 </VirtualHost>

  #3つ目のサイト
 <VirtualHost *:80>
    ServerName uslife.mossymob.tk
    DirectoryIndex index.html index.php
    AddDefaultCharset UTF-8
    DocumentRoot /var/uslife/html/ <-アクセスがあった時に最初に表示するファイルを格納するドキュメント・ルートは自由に指定してよい。
    <Directory "/var/favname/html/">
     AllowOverride All
     Options FollowSymLinks -Indexes
    </Directory>
 </VirtualHost>

など。

* < VirtualHost *:80></VirtualHost>の内容は、別ファイルを作らずに、httpd.confファイルの最後に記載しても良い。

変更したらシステムのリロードを忘れずに。

# systemctl reload httpd

追記)
wsgiを使用している場合、並列に書くだけでは、httpdがリロードさえ出来ないエラーになる、
という事が判明しました。 これを避けるための詳細な記事は、以下で解説。

【 複数のサブドメインを管理しているサーバで、wsgiを使う時のVirtual Hostの書き方   】

<Directory> ディレクティブで指定できる事項。

CustomLogアクセスログ
ErrorLogエラーログ
AddHandlerCGIスクリプトを使用するかしないか
AllowOverride.htaccessによる設定変更を有効にするかどうか
IfModuleモジュールが存在する時に処理される
RewriteEngineRewriteEngineをONにするかOFFにするか
RemoveHnadlerファイル拡張子に関連付けされたハンドラをすべて解除する
RewriteCond書き換えの条件を指定する。条件に一致したときだけ書き換え
RewriteRule書き換えのルール。パターンに一致した値を置換する




◆ Daemon Mode (Single Application)
The preferred way of setting up mod_wsgi is to run each WSGI application in its own daemon process group. This is called daemon mode. A typical configuration for running a WSGI application in daemon mode would be:

WSGIDaemonProcess myapp
WSGIProcessGroup myapp
WSGIApplicationGroup %{GLOBAL}
WSGIScriptAlias / /some/path/project/myapp.wsgi
<Directory /some/path/project>
    Require all granted
</Directory>

The WSGIDaemonProcess directive defines the daemon process group.
The WSGIProcessGroup directive indicates that the WSGI application should be run within the defined daemon process group.

As only the single application is being run within the daemon process group, the
WSGIApplicationGroup directive is also being used. When this is used with the %{GLOBAL} value, it forces the WSGI application to run in the main Python interpreter context of each process.

This is preferred in this scenario as some third party packages for Python which include C extensions will not run in the Python sub interpreter contexts which mod_wsgi would use by default. By using the main Python interpreter context you eliminate the possibility of such third party packages for Python causing problems.
To modify the configuration for this scenario to use a Python virtual environment, all you need to do is add the python-home option to the WSGIDaemonProcess directive resulting in:

WSGIDaemonProcess myapp python-home=/usr/local/venvs/myapp

2018年12月25日火曜日

これで動く (3/3) !! WebArena VPS(CentOS7)でFlaskを動かす (routingの確認)

安さに目が眩んでWebArena VPSで、Flaskを動かしてみました。 今回が最終回です。

CentOS 7 + Python 3.6 + Apache2.4 +mod_wsgi +  Flaskです。 オーソドックスな環境です。

今回は、

1.  wsgiファイルを設定する。

2. Apacheファイルを設定する。

3. Flask appをアップロードする。


これで、今回のシリーズは終了です。




1.  wsgiファイルを設定する。

 設置場所:/var/www/html

 If you don’t want to install it system wide consider using a virtual python instance. Keep in mind that you will have to actually install your application into the virtualenv as well. Alternatively there is the option to just patch the path in the .wsgi file before the import

という事なので、
ファイル名: myapp.wsgi
記述内容:


# coding: utf-8
import sys
sys.path.insert(0, '/var/www/html')

from app import app as application

[root@cnewgwb6 html]# touch myapp.wsgi
[root@cnewgwb6 html]# vi myapp.wsgi
上記をコピペ。


2. Apacheファイルを設定する。

1)  httpd.conf の修正
  Virtual Hostを使用することをapacheに教えます。
  /etc/httpd/conf/httpd.confの編集(1行)

  (修正前)
      ServerName www.example.com:80
    (修正後:コメントアウト)
    #ServerName www.example.com:80 
 
  ↑ Defaultではコメントアウトになっているので、特別に設定を変えていなければ修正不要。

    (名前ベースの VirtualHost の待受けをすることを宣言)
  記載する場所はどこでも可だが、とりあえず 'Listen 80'の下に、以下を書く。
  NameVirtualHost *:80


2)

/etc/httpd/conf.d/ の下に、virtualhost.conf を作成。


[root@ip2h3wsy httpd]# ls -a
.  ..  conf  conf.d  conf.modules.d  logs  modules  run
[root@ip2h3wsy conf.d]# touch virtualhost.conf
[root@ip2h3wsy conf.d]# vi virtualhost.conf

==ファイル名: virtualhost.conf
LoadModule wsgi_module /usr/lib64/httpd/modules/mod_wsgi.so

<VirtualHost *:80>
  ServerName mossymob.tk
 ServerAlias www.mossymob.tk
  DocumentRoot /var/www/html
  WSGIScriptAlias / /var/www/html/myapp.wsgi
  <Directory "/var/www/html/">
    Options Includes ExecCGI FollowSymLinks
  </Directory>
</VirtualHost>


*WSGIScriptAlias の書き方
  第一引数:アップのある場所  ドキュメントルートのトップと同じなら ' / ' だけで良い。
  第二引数:.wsgiファイルのある場所までのFull Path

*注意)
apache2.4から書式が変わっています、 cgiなどを許可しますが、実際にCGIを動かすには
この他にも AllowOverride All ← .htaccessの許可 とか、AddHandler cgi-script .cgi .pl ← CGIスクリプトに.plを追加 の設定が必要になるようです。
(詳細:https://qiita.com/salt_field/items/3e255c3356006a1e020f

Require all granted を</Directory>の直前に書いてもよい。

(* この書き方は、wsgiのデフォルトであるEmbeded Modeでの記述方法です。  Embeded Modeは、メモリーを多く 要すること等から問題も多く、Deamon Mode (デーモン・モード)で運用することが推奨されていますし、  Djangoを動かすときの前提でもあります。 このデーモン・モードの書き方は以下で説明しています。

 【 「 (詳述) Virtualenvとmod_wsgiで、Python Flaskを動かす  」 】)
 

以上を記載の上、システムのリロードをして設定終了。

# systemctl reload httpd

3. Flask appをアップロードする。

ドキュメント・ルート(/var/www/html)に以下のflask appをアップロード

ファイル名:app.py
# coding: utf-8
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
     return "Hello, Flask!"
if __name__ == "__main__":
     app.run( )  ←ドメイン名やポート指定を削除してます。




Browserでwww.mossymob.tk / mossymob.tk を確認。



!!よく見えないかもしれませんが、
'wwwあり'と'wwwなし'のどちらも、
きちんと表示されました。!!


さて、ここまではシェアド・ホスティングでcgiを使ってもできます。

ルーティングが出来なくては。

ということで確認。


(Directory構成)
-----html
 |-----app.py
 |---templates
   |
   |--sample01.html
   |--sample02.html

(ファイルの内容)

app.py
from flask import Flask, render_template, request
app = Flask(__name__)

@app.route('/')
def index():
    message="Hi, Charlie!"
    return render_template("sample01.html", message=message)
   
@app.route('/add',methods=['POST'])
def add():
    if request.method =='POST':
        result = request.form['new_wish'] # Formのname elementで指定する。
    #else:
    #    result = "No wish! Ah?"
       
    return render_template("sample02.html", result=result)

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



sample01.html
<html>
 <head>
   <meta charset="utf-8">
 </head>
 <body>
 {{message}}
<form action="/add" method="post"> 
<p>Input new make you wish to add to the list:</p>
<input type="text" name="new_wish" >
<input type="submit" value="Do">
</form>
 </body>
</html>
sample02.html
<meta charset="utf-8">
 </head>
 <body>
<p>Now we know the brand of the car you want is</p>
{{result}}
 </body>
</html> 


で、ルーティング( '/' --> '/add')ができるか検証です。





こちらも、問題なく、ルーティングがされていることが確認できました。

これで終わりです。



ちょっと追加)


Browserで確認すると、welcome.htmlが出てしまうことがあったので、

表示されないようにする。


[root@ofcm9och conf.d]# pwd
/etc/httpd/conf.d

[root@ofcm9och conf.d]# vi welcome.conf
#
# This configuration file enables the default "Welcome" page if there
# is no default index page present for the root URL.  To disable the
# Welcome page, comment out all the lines below.
#
# NOTE: if this file is removed, it will be restored on upgrades.

# All descriptions below from here are commented out on Dec 25,2018
# While all descriptions were commented in before this modifcation.

#<LocationMatch "^/+$">
#    Options -Indexes
#    ErrorDocument 403 /.noindex.html
#</LocationMatch>
#<Directory /usr/share/httpd/noindex>
#    AllowOverride None
#    Require all granted
#</Directory>

これで動く (2/3) !! WebArena VPS(CentOS7)でFlaskを動かす

安さに目が眩んでNTT PC のWebArena VPSで、Flaskを動かしてみました。
CentOS 7 + Python 3.6 + Apache2.4 +mod_wsgi +  Flaskです。 オーソドックスな環境です。

今回は、

1.  mod_wsgiをインストールする。

2.  flaskをインストールする。

3. flask appを用意してアップロード。




1.  mod_wsgiをインストールする。


$ cd /usr/local/src (<- Python3.6 をインストールしたのと同じディレクトリが便利。mustではない。)
$ wget https://github.com/GrahamDumpleton/mod_wsgi/archive/4.5.6.tar.gz

(最新版は、こちらで確認:https://modwsgi.readthedocs.io/en/develop/user-guides/quick-installation-guide.html


$ tar zxvf 4.5.6.tar.gz

(Apacheのextensionのapxsと、mod_wsgiをビルドするPythonのバージョンを指定する。)
(' / ' で)$ find -name apxs
  ./usr/bin/apxs

$ cd /usr/local/src/mod_wsgi-4.5.6

$ ./configure --with-apxs=/usr/bin/apxs --with-python=/usr/bin/python3
 config.status: creating Makefile
$ make && make install

Libraries have been installed in:
   /usr/lib64/httpd/modules
If you ever happen to want to link against installed libraries
in a given directory, LIBDIR, you must either use libtool, and
specify the full pathname of the library, or use the `-LLIBDIR'
flag during linking and do at least one of the following:
   - add LIBDIR to the `LD_LIBRARY_PATH' environment variable
     during execution
   - add LIBDIR to the `LD_RUN_PATH' environment variable
     during linking
   - use the `-Wl,-rpath -Wl,LIBDIR' linker flag
   - have your system administrator add LIBDIR to `/etc/ld.so.conf'
See any operating system documentation about shared libraries for
more information, such as the ld(1) and ld.so(8) manual pages.
----------------------------------------------------------------------
chmod 755 /usr/lib64/httpd/modules/mod_wsgi.so

おっ! mod_wsgi.soが出来ました。
[root@ofcm9och mod_wsgi-4.6.5]cd /usr/lib64/httpd/modules/
[root@cnewgwb6 modules]# ls -l
-rwxr-xr-x  1 root root 962648 Dec 28 11:13 mod_wsgi.so
'755' になってますね。


2. flaskをインストールする。

==ここ、エラーが出たので、その対処です。 読み飛ばしてください。==
[root@ofcm9och /]# pip3.6 install flask
pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.

エラーが出た。 SSL関連らしい。

[root@ofcm9och /]# yum list installed |grep ssl
mod_ssl.x86_64                     1:2.4.6-88.el7.centos          @base
openssl.x86_64                     1:1.0.2k-16.el7                @base
openssl-libs.x86_64                1:1.0.2k-16.el7                @base

どうも、openssl-devel がインストールできていないようなので、再インスール。
[root@ofcm9och /]# yum install openssl-devel
で、
mod_ssl.x86_64                     1:2.4.6-88.el7.centos          @base
openssl.x86_64                     1:1.0.2k-16.el7                @base
openssl-devel.x86_64               1:1.0.2k-16.el7                @base
openssl-libs.x86_64                1:1.0.2k-16.el7                @base
が、入った。

おそらく次の、ncurses-devel  も、インストール出来ていなかったろうから(多分、スペースがなかったのかと思ってる)再インストール。

ツールを再インストールしたので、python3.6.5 ディレクトリで、再度 make / make install を再実行。

== 読み飛ばし部分の終了==

(最新版の確認)
[vpsuser_p@ofcm9och /]$ python3 -m pip install flask==
Collecting flask==
  Could not find a version that satisfies the requirement flask== (from versions: 0.1, 0.2, 0.3, 0.3.1, 0.4, 0.5, 0.5.1, 0.5.2, 0.6, 0.6.1, 0.7, 0.7.1, 0.7.2, 0.8, 0.8.1, 0.9, 0.10, 0.10.1, 0.11, 0.11.1, 0.12, 0.12.1, 0.12.2, 0.12.3, 0.12.4, 1.0, 1.0.1, 1.0.2)
No matching distribution found for flask==

(最新版のインストール)
[vpsuser_p@ofcm9och /]$ python3 -m pip install flask==1.0.2
Successfully installed Jinja2-2.10 MarkupSafe-1.1.0 Werkzeug-0.14.1 click-7.0 flask-1.0.2 itsdangerous-1.1.0


3. flask appを用意してアップロード。

ドキュメント・ルート(var/www/html)に以下のflaskのappファイルをアップロード

ファイル名:app.py

# coding: utf-8
from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello, Flask!"

if __name__ == "__main__":
    app.run(host="mossymob.tk", port=8080)
*mossymob.tkは、無料で1年間取得した、自分のドメインです。


・ firewallでポートを開ける。


[root@ofcm9och html]# firewall-cmd --add-port=8080/tcp --zone=public

(一応、今回限りの使用なので、--permanentはつけない、)
success

[root@mk1ouin8 ~]#  firewall-cmd --reload   (<- reloadしたら設定が消えちゃうね)
success
[root@ofcm9och html]# firewall-cmd --list-all
public (active)
  target: default
  icmp-block-inversion: no
  interfaces: eth0
  sources:
  services: ssh dhcpv6-client http https
  ports: 8080/tcp   <= 追加されています。
  protocols:
  masquerade: no
  forward-ports:
  source-ports:
  icmp-blocks:
  rich rules:


*WebArenaなのでポータルのセキュリティー・グループでもポートを開ける。

[root@ofcm9och html]# python3 app.py
 * Serving Flask app "app" (lazy loading)
 * Environment: production
   WARNING: Do not use the development server in a production environment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://mossymob.tk:8080/ (Press CTRL+C to quit)


 
 
とりあえず、Flask Appが
Browserに表示できました。!!


(追記)
”このページは表示できません。
Web アドレス http://mossymob.tk:8080 が正しいか
確かめてください。”

というエラー表示になった場合、app.pyファイルの権限を確認してみてください。

(表示できなかったパーミッション)
-rw-r--r-- 1 root root 210 Dec 28 11:54 app.py
(*Other Groupに実行権限がない。)

(表示できたパーミッション)
-rw-r-xr-x 1 root root 210 Dec 28 11:54 app.py
(*Other Groupに実行権限を付与した。)

これで動く (1/3) !! WebArena VPS(CentOS7)でFlaskを動かす


安さに目が眩んでNTT PC の「WebArena VPS クラウド」で、Flaskを動かしてみました。
CentOS 7 + Python 3.6 + Apache2.4 +mod_wsgi +  Flaskです。 オーソドックスな環境です。

今回は、
1.Apache Install
2. SELinux 無効化
3. Firewallの設定
4. httpsの設定
5. Python3.6 とpip のインストール


1.  Apacheをインストールする。

[root@ofcm9och /]# yum list available | grep httpd
httpd.x86_64                              2.4.6-88.el7.centos            base
httpd-devel.x86_64                        2.4.6-88.el7.centos            base
httpd-manual.noarch                       2.4.6-88.el7.centos            base
httpd-tools.x86_64                        2.4.6-88.el7.centos            base
keycloak-httpd-client-install.noarch      0.6-3.el7                      base
libmicrohttpd.i686                        0.9.33-2.el7                   base
libmicrohttpd.x86_64                      0.9.33-2.el7                   base
libmicrohttpd-devel.i686                  0.9.33-2.el7                   base
libmicrohttpd-devel.x86_64                0.9.33-2.el7                   base
libmicrohttpd-doc.noarch                  0.9.33-2.el7                   base
python2-keycloak-httpd-client-install.noarch

1) httpdのインストール
# yum -y install httpd httpd-tools httpd-devel httpd-manual
Complete!

2)確認
[root@ /]# yum list installed | grep httpd

[root@ofcm9och /]# yum list installed | grep httpd
httpd.x86_64                       2.4.6-88.el7.centos            @base
httpd-devel.x86_64                 2.4.6-88.el7.centos            @base
httpd-manual.noarch                2.4.6-88.el7.centos            @base
httpd-tools.x86_64                 2.4.6-88.el7.centos            @base


3)  起動する。
# systemctl start httpd


4) 起動の状態を確認する。
$ systemctl status httpd

httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; vendor preset: disabled)
   Active: active (running) since Mon 2018-12-24 23:32:33 JST; 23s ago
     Docs: man:httpd(8)
           man:apachectl(8)
 Main PID: 1338 (httpd)
   Status: "Total requests: 0; Current requests/sec: 0; Current traffic:   0 B/sec"
   CGroup: /system.slice/httpd.service
           tq1338 /usr/sbin/httpd -DFOREGROUND
           tq1339 /usr/sbin/httpd -DFOREGROUND
           tq1340 /usr/sbin/httpd -DFOREGROUND
           tq1341 /usr/sbin/httpd -DFOREGROUND
           tq1342 /usr/sbin/httpd -DFOREGROUND
           mq1343 /usr/sbin/httpd -DFOREGROUND

Dec 24 23:32:33 ofcm9och systemd[1]: Starting The Apache HTTP Server...
Dec 24 23:32:33 ofcm9och httpd[1338]: AH00557: httpd: apr_sockaddr_info_get...ch
Dec 24 23:32:33 ofcm9och httpd[1338]: AH00558: httpd: Could not reliably de...ge
Dec 24 23:32:33 ofcm9och systemd[1]: Started The Apache HTTP Server.
Hint: Some lines were ellipsized, use -l to show in full.


5) httpd自動起動の設定
$ systemctl enable httpd
(確認)
systemctl list-unit-files | grep httpd
httpd.service                                 enabled


2. SELinuxの無効化

1) 現状の確認
[root@ /]# sestatus
SELinux status:                 enabled


2)Configファイルのコピーを保存。(??)
[root@ /]# cp -piv /etc/selinux/config /etc/selinux/config.`date "+%Y%m%d_%H%M%S
"`
‘/etc/selinux/config’ -> ‘/etc/selinux/config.20181223’



3) Configファイルの修正
[root@ /]# cd  /etc/selinux/
[root@ selinux]# vi config

#SELINUX=enforcing
SELINUX=disabled


4) OSの再起動
shutdown -r now


5)再確認
[root@ /]#  sestatus
SELinux status:                 disabled
 


6httpd自動起動の設定

[root@ /]# systemctl enable httpd
[root@ /]# systemctl list-unit-files | grep httpd

httpd.service                                 enabled

3. Firewallを設定する。

1) ファイアウォールが起動中かどうかを確認

# firewall-cmd --state
running

2) ファイアウォール設定を確認
# firewall-cmd --list-all

public (active)
  target: default
  icmp-block-inversion: no
  interfaces: eth0
  sources:
  services: ssh dhcpv6-client
  ports:
  protocols:
  masquerade: no
  forward-ports:
  source-ports:
  icmp-blocks:
  rich rules:

3) http/httpsのサービス追加
[root@ ~]# firewall-cmd --zone=public --add-service=http --permanent
success
[root@ ~]# firewall-cmd --zone=public --add-service=https --permanent
success
[root@ ~]# firewall-cmd --list-all <- ここでやっても変化なし。 リロード要。
[root@ /]# firewall-cmd --reload
success
# firewall-cmd --list-all
 public (active)
  target: default
  icmp-block-inversion: no
  interfaces: eth0
  sources:
  services: ssh dhcpv6-client http https
  ports:       <- 後日、ポート番号を指定して解放する。
  protocols:
  masquerade: no
  forward-ports:
  source-ports:
  icmp-blocks:
  rich rules:


4. https通信に関する設定する。

1) mod_sslがインストールされているかの確認。
 (Loaded Modulesの確認): # httpd -M
  又は
 (Installed Packagesの確認): #yum list installed | grep mod_ssl

 この段階では、両方とも、何も検知しない。

2) mod_sslのインストール
[root@ /]# yum install mod_ssl
Complete!

3)再起動で変更を反映します。
 # systemctl restart httpd

4) (Loaded Modulesの確認): # httpd -M   
 ssl_module (shared)

ブラウザで表示できることの確認、
OK

5. Python3.6 とpip のインストール

CentOSで必要なパッケージをインストールします。

# yum groupinstall "development tools"
Complete!
#yum install zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel
Complete!
#yum install httpd-devel python-devel
Package httpd-devel-2.4.6-88.el7.centos.x86_64 already installed and latest version
Package python-devel-2.7.5-76.el7.x86_64 already installed and latest version
Nothing to do

Group Listの "Development Tools"のインストール方法が変わりました。
# yum --setopt=group_package_types=mandatory,default,optional groupinstall "Development Tools"
 など。

詳細:  * Development tool for CentOS / RHEL 7

Pythonをソースからインストールする。

# cd /usr/local/src  このディレクトリに入れて管理することはとても大事。

[root@ofcm9och src]# yum -y install wget
[root@ofcm9och src]#wget https://www.python.org/ftp/python/3.6.8/Python-3.6.8.tgz

[root@ofcm9och src]# ls -a
.  ..  Python-3.6.8.tgz


[root@ofcm9och src]# tar zxvf Python-3.6.8.tgz
[root@ofcm9och src]# cd Python-3.6.8
[root@ofcm9och Python-3.6.8]# ./configure --enable-shared
[root@ofcm9och Python-3.6.8]# ./configure --enable-optimizations <- Note1)
[root@ofcm9och Python-3.6.8]# make && make altinstall
zipimport.ZipImportError: can't decompress data; zlib not available
make: *** [altinstall] Error 1


**Note 1) added on Jan.2019
何度か、ソースコードからpythonをビルドした時に気が付いたのだが、./configure --enable-shared を実行すると、「効率的なシステム構築の為に、 ./configure --enable-optimizations を実行することを合わせて考えてください。」というメッセージが出るので、実行していたが、このコマンドを実行すると、シェアド・ライブラリ用のファイル libpython3.7m.so が作成されないようだ。 wsgiは、shared library を使うことを強く推奨しているので、 ./configure --enable-optimizations は実行してはいけない。




[root@ofcm9och Python-3.6.8]# yum list available | grep zlib-devel
zlib-devel.i686                           1.2.7-18.el7                   base
zlib-devel.x86_64                     1.2.7-18.el7                   base

[root@ofcm9och Python-3.6.8]# yum list installed | grep zlib-devel
入らなかった?

[root@ofcm9och Python-3.6.8]# yum install zlib-devel
Complete!
[root@ofcm9och Python-3.6.8]# make && make altinstall
Collecting setuptools
Collecting pip
Installing collected packages: setuptools, pip
Successfully installed pip-18.1 setuptools-40.6.2
↑ This comment will come up when Python 3.6 is installed successfully.

次に、シンボリックリンクを作成する。

シンボリック・リンクとは
ln -s」で、ファイルの“シンボリックリンク”を作成できます。シンボリックリンクは、いわばファイルの“別名”で、長いファイル名に別の名前を付けたり、パス名の指定が分かりにくい場所にあるファイルを扱いやすくしたりする(例:ディレクトリへのシンボリックリンク)場合に使います。

ln -s ファイル名 リンク名
(ファイルのシンボリックリンクを作成する)
以下の実行例では、ファイル「mylist02.txt」に対し、「latest」という名前のシンボリックリンクを作成しています。この場合、テキストエディタで「latest」というファイルを編集したり、閲覧したりすることは、「mylist02.txt」を編集したり、閲覧したりすることと同じ操作結果になります。

==【例】==
1.$ ls -l
2.合計 8
3.-rw-rw-r--. 1 study study 65 5月 15 00:00 mylist01.txt
4.-rw-rw-r--. 1 study study 127 5月 17 00:00 mylist02.txt
「mylist01.txt」というファイルと「mylist02.txt」というファイルがある

$ ln -s mylist02.txt latest
「ln -s」で「mylist02.txt」に「latest」という名前のシンボリックリンクを作成する
$ ls -l
2.合計 8
3.lrwxrwxrwx. 1 study study  12  5月 18 19:39 latest -> mylist02.txt
4.-rw-rw-r--. 1 study study  65  5月 15 00:00 mylist01.txt
5.-rw-rw-r--. 1 study study 127  5月 17 00:00 mylist02.txt 
==【例 おわり】==


この理解にもとづき、最初に現状の確認。

[root@ofcm9och /]# cd /usr/local/bin
[root@ofcm9och bin]# ls -a
.   2to3-3.6          idle3.6  pydoc3.6   python3.6m         pyvenv-3.6
..  easy_install-3.6  pip3.6   python3.6  python3.6m-config

[root@ofcm9och bin]# cd /
[root@ofcm9och /]# cd usr/bin
[root@ofcm9och bin]# ls -a
python
ab                     gtroff                    python2
aclocal                gunzip                python2.7
aclocal-1.13           gzexe              python2.7-config
acpi_listen            gzip                 python2-config
addr2line              h2ph                python-config <- python3は無い。


(Symbolic Linkの作成:python3.6(実在)にpython3というリンクを作る)

$ ln -s /usr/local/bin/python3.6 /usr/bin/python3

[root@ofcm9och bin]# ln -s /usr/local/bin/python3.6 /usr/bin/python3
[root@ofcm9och bin]# ls -a
.                        gsoelim               pwmake
..                       gstack                  pwscore
[                        gtar                      pydoc
a2p                    gtbl                     python
ab                      gtroff                  python2
aclocal              gunzip                 python2.7
aclocal-1.13      gzexe                  python2.7-config
acpi_listen        gzip                     python2-config
addr2line           h2ph                   python3  <- 出来た。

=============================================
 
この段階で、python3.7 とコマンドをうっても、起動できません。
以下のようなエラーになります。
[ ~]# python3.6
python3.7: error while loading shared libraries: libpython3.6m.so.1.0: cannot open shared object file: No such file or directory


[root@ofcm9och bin]# cd /
[root@ofcm9och /]# cd /usr/local/lib
[root@ofcm9och lib]# ls -a
.   libpython3.6m.so      libpython3.so  python3.6
..  libpython3.6m.so.1.0  pkgconfig
[root@ofcm9och /]# find -name lib64
./usr/lib/debug/usr/lib64
./usr/lib/debug/lib64
./usr/lib64
./usr/share/gdb/auto-load/usr/lib64
./usr/share/gdb/auto-load/lib64
./usr/local/lib64
./usr/src/kernels/3.10.0-957.1.3.el7.x86_64.debug/arch/sh/lib64
./lib64


$ ln -s /usr/local/lib/libpython3.6m.so.1.0 /lib64/


[root@ofcm9och /]# ln -s /usr/local/lib/libpython3.6m.so.1.0 /lib64/
[root@ofcm9och /]# find -name libpython3.6m.so.1.0
./usr/lib64/libpython3.6m.so.1.0
./usr/local/lib/libpython3.6m.so.1.0
./usr/local/src/Python-3.6.8/libpython3.6m.so.1.0

[root@ofcm9och /]# python3.6 --version # 最後にバージョンの確認ができればpythonのインストール完了
Python 3.6.8

[root@ofcm9och /]# which python <- pythonだけだとデフォルト
/usr/bin/python
[root@ofcm9och /]# python -V
Python 2.7.5



これで、python3.6 というコマンドで起動できるようになりました。

[ /]# python3.6
Python 3.6.2 (default, Jan 15 2019, 21:24:34)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

=============================================


# 同時にpip3.6もインストールされるので、シンボリックリンクを貼る
[root@ofcm9och /]# python -m pip -V
/usr/bin/python: No module named pip


[root@ofcm9och /]# cd /usr/local/bin
[root@ofcm9och bin]# ls -a
.   2to3-3.6          idle3.6  pydoc3.6   python3.6m         pyvenv-3.6
..  easy_install-3.6  pip3.6   python3.6  python3.6m-config


[root@ofcm9och bin]# cd /
[root@ofcm9och /]# cd usr/bin
[root@ofcm9och bin]# ls -a   <- pipは存在しない。

git                                  pic                      which
git-receive-pack            piconv                 whiptail
git-shell                         pinentry               who
git-upload-archive         pinentry-curses    whoami
git-upload-pack             ping                      write
glib-compile-schemas   ping6                     x86_64
gmake                           pinky                     x86_64-redhat-linux-c++



$ ln -s /usr/local/bin/pip3.6 /usr/bin/pip3.6


[root@ofcm9och bin]# ln -s /usr/local/bin/pip3.6 /usr/bin/pip3.6
[root@ofcm9och bin]# ls -a  (symlinkが作成された)

glib-compile-schemas   pinky                     x86_64-redhat-linux-c++
gmake                  pip3.6                    x86_64-redhat-linux-g++


[root@ofcm9och bin]# python -m pip -V
/usr/bin/python: No module named pip
[root@ofcm9och bin]# python3 -m pip -V
pip 18.1 from /usr/local/lib/python3.6/site-packages/pip (python 3.6)


python3 に紐づいたpipのバージョンが18.1 と確認できたところで、
今回は終了です。