Saturday, January 27, 2018

How to use Ansible

Prerequisites

  • I'm using windows8 and using virtual CentOS 7.3 in windows local as Ansible's host machine. If you don't have Linux or Mac, use virtual machine like I do. But in that case, don't forget to set the host's IP adress to 198.168.33.11 because duplicate IP causes an error.
  • As such, we will use two virtual machines in Windows.
    1. Host (CentOS7.3, IP:192.168.33.11).
    2. Guest (CentOS7.3, IP:192.169.33.10).
See here for virtual machines. (If you use two VMs, strictly speaking, it isn't host-guest relationship. But let me use the term for simplicity and because I don't know how to call it. Central and Others?)

Why Ansible?

Without Ansible, you need to do everything written here manually (to create PHP development environment for vagrant/virtualbox). Let's do it automatically with Ansible.

Install Ansible

At first, install python3.5 from IUS repository.
$ sudo rpm -Uvh https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
$ sudo yum install -y https://centos7.iuscommunity.org/ius-release.rpm
$ sudo yum install -y python35u python35u-libs python35u-devel python35u-pip
And install ansible.
$ sudo pip3.5 install ansible
$ sudo yum install -y sshpass 
And check if you have installed it successfully.
$ ansible --version
ansible 2.5.5
  config file = None
  configured module search path = ['/home/vagrant/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python3.5/site-packages/ansible
  executable location = /usr/bin/ansible
  python version = 3.5.5 (default, Feb  6 2018, 10:57:32) [GCC 4.8.5 20150623 (Red Hat 4.8.5-16)]
We installed ansible from pip. So we don't have /etc/ansible/ansible.cfg. You can create the cfg file by yourself. The default file can be found in their github. See their documentation too.

Add hosts information

Run the following to create hosts file in the host machine:
$ sudo mkdir /etc/ansible/
$ sudo vi /etc/ansible/hosts
Write as follows:
[nodes]
192.168.33.10
And save and close it by pressing :wq.
Also run this command too:
$ sudo vi /etc/ansible/ansible.cfg
Then write as follows:
[defaults]
host_key_checking = false
Then save and close it.

Basic command of Ansible

$ ansible 192.168.33.10 -m ping 192.168.33.10 : IP address of the machine in which you want to deploy an environment via Ansible. -m ping: m option means module. ping is the module name.
Usually ansible is used with public keys to connect to guest machines. But it's difficult (if you want to try, you can check it here for example). So we simply use password to login the guest machine. Run the following command. SSH password is vagrant:
$ sudo ansible 192.168.33.10 -m ping -u vagrant -k
If you successfully have done everything, you will see this:

Install packages with playbook

Create a playbook
$ cd /vagrant
$ sudo touch dstat.yaml
$ sudo vi /vagrant/dstat.yaml
Write as follows inside dstat.yaml
- hosts: 192.168.33.10
  tasks:
   - name: Install dstat
     become: yes
     become_method: sudo
     yum: pkg=dstat state=installed update_cache=true
Save and close it by :wq. Then use the playbook.
$ ansible-playbook -s dstat.yaml -u vagrant -k
If everything worked successfully, dstat is installed automatically in the guest machine. Check it by running
$ dstat
in the guest machine. If the following was displayed, you successfully did everything.

Create a playbook for PHP development environment

Use this playbook to create PHP development environment automatically in CentOS 7.3 whose IP address is 192.168.33.10. See here for yum operaion in Ansible.
Save the following as "php.yaml":
- hosts: 192.168.33.10
  tasks:
    - name: Update yum
      become: yes
      become_method: sudo
      yum: 
        name: '*' 
        state: latest
    - name: Install apache
      become: yes
      become_method: sudo
      yum: pkg=httpd state=latest update_cache=true
    - name: Add epel 7 to /etc/yum.repos.d/
      become: yes
      become_method: sudo
      yum_repository:
        name: epel
        description: EPEL YUM repo
        baseurl: https://download.fedoraproject.org/pub/epel/$releasever/$basearch/
        gpgkey: https://archive.fedoraproject.org/pub/epel/RPM-GPG-KEY-EPEL-7
    - name: Add IUS repository to /etc/yum.repos.d/
      yum_repository:
        name: ius
        file: ius
        description: IUS Community Packages for Enterprise Linux 7 - $basearch
        mirrorlist: https://mirrors.iuscommunity.org/mirrorlist?repo=ius-centos7&arch=$basearch&protocol=http
        gpgkey: http://dl.iuscommunity.org/pub/ius/IUS-COMMUNITY-GPG-KEY
        enabled: yes
        gpgcheck: yes
    - name: Update yum again
      become: yes
      become_method: sudo
      yum: 
        name: '*' 
        state: latest
    - name: Install php packages
      become: yes
      become_method: sudo
      yum: 
        name:
          - php71u
          - php71u-mysqlnd
          - php71u-gd
          - php71u-mbstring
          - php71u-opcache
          - php71u-xml
          - php71u-pecl-xdebug
          - php71u-pdo
          - php71u-devel
          - php71u-json
    - name: Add MySQL repo 
      become: yes
      become_method: sudo
      yum:
        name: https://dev.mysql.com/get/mysql57-community-release-el7-11.noarch.rpm
    - name: Install MySQL
      become: yes
      become_method: sudo
      yum: 
        name: "mysql-server" 
        state: present
    - service: name=httpd state=started enabled=yes
    - service: name=mysqld state=started enabled=yes
    - name: Install other necessary packages
      become: yes
      become_method: sudo
      yum: 
        name:
          - kernel-devel
          - kernel-headers
          - dkms
          - gcc
          - gcc-c++
And use it like this:
$ ansible-playbook -s php.yaml -u vagrant -k
And the PHP development environment is automatically created in the guest machine.

Sunday, January 21, 2018

How to use Chef and create Laravel environment automatically

Follow steps written here and create basic cookbooks for PHP environment.

After that, you should have cookbooks like this:


Create Virtual Box for chef


We will create a virtual server. Create a folder for the virtual server and Vagrant and run these commands on Command Prompt. (Not Powershell now)


(If you don't know how to use Vagrant and Virtual box)

cd C:\Users\John\Documents\vagrant\CentOsChef
vagrant init bento/centos-7.3



Change the file "Vagrantfile" and use the private network.

And start the virtual server.
vagrant up

Please make sure there is ".ssh" folder in C:\Users\John. If not, create the folder by running this command:
cd C:\Users\John
mkdir .ssh





After that, run these commands:
cd C:\Users\John\Documents\vagrant\CentOsChef
vagrant ssh-config --host CentOsChef >> %USERPROFILE%/.ssh/config
"CentOsChef" is a name of your virtual machine. "ssh-config" is a command to create a file and to make connection to the virtual machine easier. If there is old ssh-config information using a same alias name, delete the old one and leave only the new one.

Create a cookbook for laravel


Open Powershell (ChefDK) and go to the folder of Chef on Powershell:
cd C:\Users\John\Documents\chef

Create a cookbook for laravel environment.
chef generate cookbook cookbooks/proj_laravel


Update the virtual machine so that the shared folder works


And create a new cookbook for updating vagrant:
chef generate cookbook cookbooks/vagrant_update

Add depends 'yum-ius' in chef\cookbooks\vagrant_update\metadata.rb.
Add cookbook 'yum-ius' in chef\cookbooks\vagrant_update\Berksfile.
Add the following in chef\cookbooks\vagrant_update\recipes\default.rb:
include_recipe 'yum-ius'

package ['kernel-devel', 'kernel-headers', 'dkms', 'gcc', 'gcc-c++'] do
  action   :install
end

package 'kernel' do
  action   :upgrade
end


Update the cookbook of laravel



Add the following in chef\cookbooks\proj_laravel\Berksfile
apps_path = 'C:/Users/Shu/Documents/chef/cookbooks/'
cookbook 'vagrant_update',     path: apps_path + 'vagrant_update'
cookbook 'app_httpd',           path: apps_path + 'app_httpd'
cookbook 'app_mysql_server', path: apps_path + 'app_mysql_server'
cookbook 'app_php71u',             path: apps_path + 'app_php71u'
cookbook 'app_php71u_mysqlnd',     path: apps_path + 'app_php71u_mysqlnd'

Add the following in chef\cookbooks\proj_laravel\metadata.rb
depends 'vagrant_update'
depends 'app_httpd'
depends 'app_mysql_server'
depends 'app_php71u'
depends 'app_php71u_mysqlnd'

Add the following in chef\cookbooks\proj_laravel\recipes\default.rb
include_recipe 'vagrant_update'
include_recipe 'app_httpd'
include_recipe 'app_mysql_server'
include_recipe 'app_php71u'
include_recipe 'app_php71u_mysqlnd'

service 'httpd' do
    action :restart
end

service 'mysqld' do
    action :restart
end

bash 'install_composer' do
  code <<-EOH
    curl -sS https://getcomposer.org/installer | php
    mv composer.phar /usr/local/bin/composer
    EOH
end

bash 'laravel_install' do
  code <<-EOH
    cd /vagrant
    curl -sS https://getcomposer.org/installer | php
    mv composer.phar /usr/local/bin/composer
    composer create-project --prefer-dist laravel/laravel laravel
  EOH
end

bash 'set_permission' do
  code <<-EOH
    chmod -R 777 /vagrant/laravel/storage
  EOH
end

ruby_block "httpd conf replace to make allowOverride all" do
  block do
    fe = Chef::Util::FileEdit.new("/etc/httpd/conf/httpd.conf")
    fe.search_file_replace(/\<Directory \"\/var\/www\/html\"\>[\s\S\n]*?\<\/Directory\>/,
                               "<Directory \"/var/www/html\" />Options FollowSymLinks\nAllowOverride All\nRequire all granted\n</Directory>")
    fe.write_file
  end
end

ruby_block "httpd conf replace to change document root" do
  block do
    fe = Chef::Util::FileEdit.new("/etc/httpd/conf/httpd.conf")
    fe.search_file_replace(/DocumentRoot \"\/var\/www\/html\"/,
                               "DocumentRoot \"/var/www/html/laravel/public\"")
    fe.write_file
  end
end

service 'httpd' do
    action :restart
end

service 'mysqld' do
    action :restart
end

Then update the Chef files on Powershell (ChefDK).
berks vendor -b cookbooks/proj_cake3/Berksfile --delete

Start creating the Laravel environment.
knife zero bootstrap CentOsChef -N chef_laravel -z -r 'recipe[proj_laravel]' --sudo

Wait for a while until the result appears on Powershell (ChefDK)....
If all of them worked successfully, you can access http://192.168.33.10/ and see the laravel's top page.








But maybe you need to manually do:
composer install
php artisan key:generate

Saturday, January 20, 2018

How to use Chef and create PHP environment automatically

At first, download and install Chef:
https://downloads.chef.io/chefdk

You can download Chef installer for Windows from the website:


After installing it, start Chef:

You will see the Powershell of Windows:


Run this command and hit y on the keyboard.
Set-ExecutionPolicy RemoteSigned
Close ChefDK and restart it.

Create a folder for Chef. For example, C:\Users\John\Documents\chef.


Go to the folder on Powershell.
cd C:\Users\John\Documents\chef

Install knife-zero on Powershell:
gem install knife-zero

And create a project of Chef:
chef generate repo .

Folders of Chef will be created like this:

Delete the example folders. And create "config.rb" which is used as a configuration file.
rm -d -force -r cookbooks/example
rm -d -force -r data_bags/example
rm -force -r environments/example.json
rm -force -r roles/example.json
touch config.rb

Add "berks-cookbooks" in ".gitignore". (Anywhere is OK except behind #.)

Add "cookbook_path ['berks-cookbooks']" in the folder "config.rb".


Create a project:
chef generate cookbook cookbooks/proj_lamp

Now we will create a virtual server. Create a folder for the virtual server and Vagrant and run these commands on Command Prompt. (Not Powershell now)


(If you don't know how to use Vagrant and Virtual box)

cd C:\Users\John\Documents\vagrant\CentOsChef
vagrant init bento/centos-7.3



Change the file "Vagrantfile" and use the private network.

And start the virtual server.
vagrant up

Please make sure there is ".ssh" folder in C:\Users\John. If not, create the folder by running this command:
cd C:\Users\John
mkdir .ssh





After that, run these commands:
cd C:\Users\John\Documents\vagrant\CentOsChef
vagrant ssh-config --host CentOsChef >> %USERPROFILE%/.ssh/config
"CentOsChef" is a name of your virtual machine. "ssh-config" is a command to create a file and to make connection to the virtual machine easier.

Now, on Powershell, run these commands to create cookbooks:
cd C:\Users\John\Documents\chef
chef generate cookbook cookbooks/app_httpd
chef generate cookbook cookbooks/app_mysql_server
chef generate cookbook cookbooks/app_php71u
chef generate cookbook cookbooks/app_php71u_mysqlnd

Cookbook to Install httpd


Open the folder cookbooks/app_httpd and add cookbook 'yum-ius' in the file chef/cookbook/app_httpd/Berksfile like this:





Add depends 'yum-ius' in chef/cookbook/app_httpd/metadata.rb:




Add the following in chef/cookbook/app_httpd/recipes/default.rb
include_recipe 'yum-ius'

package 'httpd' do
  action   :install
end

bash 'link_html' do
  code <<-EOH
    sudo rm -rf /var/www/html
    sudo ln -fs /vagrant /var/www/html
    EOH
end

service 'httpd' do
    action [:enable, :start]
end




Cookbook to Install MySQL


Add cookbook 'yum-ius' in chef\cookbooks\app_mysql_server\Berksfile.
Add depends 'yum-ius' in chef\cookbooks\app_mysql_server\metadata.rb.
Add the following in chef\cookbooks\app_mysql_server\default.rb :
include_recipe 'yum-ius'

package ['mariadb-server', 'mariadb-libs'] do
  action   :remove
end

bash 'wget_mysql' do
  code <<-EOH
    cd /vagrant
    wget https://dev.mysql.com/get/mysql57-community-release-el7-11.noarch.rpm
    EOH
end

bash 'rpm_mysql57' do
  code <<-EOH
    cd /vagrant
    sudo rpm -ivh mysql57-community-release-el7-11.noarch.rpm
    EOH
end

package 'mysql-server' do
  action   :install
end

service 'mysqld' do
    action [:enable, :start]
end

Cookbook to Install PHP

Add cookbook 'yum-ius' in chef\cookbooks\app_php71u\Berksfile.
Add depends 'yum-ius' in chef\cookbooks\app_php71u\metadata.rb.
Add the following in chef\cookbooks\app_php71u\recipes\default.rb.
include_recipe 'yum-ius'

package ['php', 'mod_php', 'php-common', 'php-cli', 'php-intl', 'php-json', 'php-mbstring', 'php-xml'] do
  action   :remove
end

# for any framework
package 'php71u'
package 'php71u-cli'
package 'php71u-intl'
package 'php71u-json'
package 'php71u-mbstring'
package 'php71u-xml'

Add cookbook 'yum-ius' in chef\cookbooks\app_php71u_mysqlnd\Berksfile.
Add depends 'yum-ius' in chef\cookbooks\app_php71u_mysqlnd\metadata.rb.
Add ci-dessous in chef\cookbooks\app_php71u_mysqlnd\recipes\default.rb.
include_recipe 'yum-ius'

# libmysql is windows only
package ['php-mysql', 'php-mysqli', 'php-pdo', 'php-mysqlnd'] do
  action   :remove
end

# for any framework
package 'php71u-mysqlnd'
package 'php71u-pdo'


Update the project


Add the following in chef/cookbooks/proj_lamp/Berksfile
apps_path = 'C:/Users/John/Documents/chef/cookbooks/'
cookbook 'app_httpd',           path: apps_path + 'app_httpd'
cookbook 'app_mysql_server', path: apps_path + 'app_mysql_server'
cookbook 'app_php71u',             path: apps_path + 'app_php71u'
cookbook 'app_php71u_mysqlnd',     path: apps_path + 'app_php71u_mysqlnd'


Add the following in chef/cookbooks/proj_lamp/metadata.rb
depends 'app_httpd'
depends 'app_mysql_server'
depends 'app_php71u'
depends 'app_php71u_mysqlnd'

Add the following in chef/cookbooks/proj_lamp/recipes/default.rb
include_recipe 'app_httpd'
include_recipe 'app_mysql_server'
include_recipe 'app_php71u'
include_recipe 'app_php71u_mysqlnd'

service 'httpd' do
    action :restart
end

service 'mysqld' do
    action :restart
end

Run these commands and update the project:
berks update -b cookbooks/proj_lamp/Berksfile
berks vendor -b cookbooks/proj_lamp/Berksfile --delete

Finally, create PHP environment in a server "CentOsChef":
knife zero bootstrap CentOsChef -N chef_lamp -z -r 'recipe[proj_lamp]' --sudo
And the PHP environment will be created in your virtual server automatically.

If you want to run knife zero bootstrap.... again, make sure that there is no "chef_lamp.json" in the folders "chef\clients" and "chef\nodes". If there is "chef_lamp.json" in either of them, knife zero bootstrap.... doesn't work and just gets hung.

Sunday, January 14, 2018

If you face errors because of permissions in the shared folder

If you face errors because of permissions in the shared folder, run this command to change the folder's owner to apache:
$ sudo chown -R apache:apache /vagrant/cake

If this doesn't work, add this line as it is in Vagrantfile:
config.vm.synced_folder "./", "/vagrant", owner: 'vagrant', group: 'apache', mount_options: ['dmode=777', 'fmode=777']

And "vagrant reload".

If even that didn't work, it might be because of SE linux. Turn off SE linux this way:
$ sudo getenforce
Enforcing
$ sudo setenforce 0
$ sudo getenforce
Permissive

And "vagrant reload".

Saturday, January 13, 2018

How to use Selenium

At first, install python3 from here: Installer Python3 dans Windows

Start your virtual machine (see here if you don't know how to start the virtual machine):
https://surlaprogrammation.blogspot.jp/2017/08/virtual-box-et-vagrant.html

And go to the virtual machine's website that you want to test (usually it's here if you are using vagrant): http://192.168.33.10/

Install Chromedriver (for your host machine):
https://sites.google.com/a/chromium.org/chromedriver/downloads

And change the location of the driver to your workspace, like "C:\Users\John\Documents\workspace\test" for example.


Do the following command on cmd.
pip install selenium

Write as follows in a text file and change it to a python file (.txt -> .py):
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException

driver_path = "C:\\Users\\John\\Documents\\workspace\\test\\chromedriver.exe" #Changez ici

driver = webdriver.Chrome(driver_path)
driver.get("http://192.168.33.10")
title = driver.find_element_by_tag_name("title")
driver.quit()
#driver.close()

Do the following commands and start the python program which we created just now.
cd C:\Users\John\Documents\workspace\test
python test.py

It will automatically start Chrome and go to http://192.168.33.10 and check the existence of "title" element in the page. (If it doesn't find the tag, it will throw an exception and stops the execution).

Monday, January 8, 2018

Add a scroll bar on a window (java Swing)

This is the code:
import javax.swing.*;
import java.awt.BorderLayout;

public class Main extends JFrame{ //Extending JFrame

 Main(){ //Constructor of Main class
     JTextArea textarea = new JTextArea("This is the JTextArea");

     JScrollPane scrollpane = new JScrollPane(); //This is the scroll bar
     scrollpane.setViewportView(textarea);

     getContentPane().add(scrollpane, BorderLayout.CENTER);
  }

 public static void main(String[] args) {
     Main frame = new Main();

     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     frame.setBounds(10, 10, 300, 200);
     frame.setTitle("This is the title");
     frame.setVisible(true);
 }
}

If you execute the code above, you will see a window will popup:

If you add line breaks a lot, the scroll bar will appear automatically:



Sunday, January 7, 2018

Installation of Tomcat9 in Cent OS 7

Update yum with epel:
$ sudo rpm -Uvh https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm

Install java8:
$ sudo yum install java-1.8.0-openjdk.x86_64

Check if java was successfully installed.
$ java -version
openjdk version "1.8.0_151"
OpenJDK Runtime Environment (build 1.8.0_151-b12)
OpenJDK 64-Bit Server VM (build 25.151-b12, mixed mode)

Create a user and a group four tomcat.
sudo groupadd tomcat
sudo mkdir /opt/tomcat
sudo useradd -s /bin/nologin -g tomcat -d /opt/tomcat tomcat

Install tomcat9.
cd ~
wget http://www.us.apache.org/dist/tomcat/tomcat-9/v9.0.2/bin/apache-tomcat-9.0.2.tar.gz
sudo tar -zxvf apache-tomcat-9.0.2.tar.gz -C /opt/tomcat --strip-components=1

Change the permission of some files. (Note: these commands will change permissions of bin, lib etc, so some softwares might not work after doing these commands.)
cd /opt/tomcat
sudo chgrp -R tomcat conf
sudo chmod g+rwx conf
sudo chmod g+r conf/*
sudo chown -R tomcat logs/ temp/ webapps/ work/

sudo chgrp -R tomcat bin
sudo chgrp -R tomcat lib
sudo chmod g+rwx bin
sudo chmod g+r /bin/*

Create a Systemd unit file of tomcat:
sudo vi /etc/systemd/system/tomcat.service

Write like the following in the file (just copy and paste the following):
[Unit]
Description=Apache Tomcat Web Application Container
After=syslog.target network.target

[Service]
Type=forking

Environment=JAVA_HOME=/usr/lib/jvm/jre
Environment=CATALINA_PID=/opt/tomcat/temp/tomcat.pid
Environment=CATALINA_HOME=/opt/tomcat
Environment=CATALINA_BASE=/opt/tomcat
Environment='CATALINA_OPTS=-Xms512M -Xmx1024M -server -XX:+UseParallelGC'
Environment='JAVA_OPTS=-Djava.awt.headless=true -Djava.security.egd=file:/dev/./urandom'

ExecStart=/opt/tomcat/bin/startup.sh
ExecStop=/bin/kill -15 $MAINPID

User=tomcat
Group=tomcat

[Install]
WantedBy=multi-user.target

And save the file by hitting ":wq".

Install haveged for secutrity.
sudo yum install haveged
sudo systemctl start haveged.service
sudo systemctl enable haveged.service

Start tomcat:
sudo systemctl start tomcat.service
sudo systemctl enable tomcat.service

Now you can see tomcat's top page: http://(your url):8080/
If you can't, change the setting of Firewall (pare-feu):
sudo firewall-cmd --zone=public --permanent --add-port=8080/tcp
sudo firewall-cmd --reload

We will create an admin user. Open "tomcat-users.xml":
sudo vi /opt/tomcat/conf/tomcat-users.xml

Add the following between "</tomcat-users ...>" and "</tomcat-users>" in the file.
<user username="admin" password="admin" roles="manager-gui,admin-gui"/>

Restart tomcat.
sudo systemctl restart tomcat.service

Now you can see the top page from a browser: http://(your url):8080/



Thursday, January 4, 2018

How to start Jenkins (windows)

Installation of Jenkins


At first, install Java8 if you haven't installed it yet.

Now download Jenkins from here: https://jenkins-ci.org/
And start the installation of Jenkins.


On CMD, go to the directory where you installed Jenkins and start Jenkins:
cd "C:\Program Files (x86)\Jenkins"
java -jar jenkins.war

Now, on a browser, go to "http://localhost:8080" and write your password. The password should be at:
C:\Program Files (x86)\Jenkins\secrets\initialAdminPassword

The following will be displayed. Click "Install suggested plugins":

Create an account of administrator. Now click "Start using Jenkins".





Create a job


Click on "create new jobs" or "New item".

Any name is ok for the name of job. Enter a name as you like. Click on "Freestyle project" and then "OK".


Then you will see the following.


Scroll down and look for "Build". Then click on "Add build step". Then, if you are using Windows, click on "Execute Windows batch command". If you are using Mac, click on "Execute shell".

And add this in the command:
echo "Hello jenkins!"



Now click on "Save".


Start the job


You will be redirected to the page of the project. Click on the "Build Now" to start the job.



After clicking "Build Now", you will see a result is added. Click the result added just now.

You will see the following. Click "Console Output":



This is the result of console. Blue symbol next to the "Console Output" means execution of the job was success. Red means failure. Yellow means unstable. The symbol is blue, so the job was executed successfully. Yay!! :)



Wednesday, January 3, 2018

Install Django (with python3)

We will use CentOS7 and vagrant.

At first, install "git" like this:
$ sudo yum install -y git

Check if pip of python3 is installed:
$ python3.6 -m pip --version

If pip of python3 is installed, this will be displayed.

Some other tutorial might say we need "virtualenv" but we don't install it because python3 has "pyenv" and we can use this instead of virtualenv. But if you want to use Django with python2, installing virtualenv is essential.

Create a folder of pyenv with python3.6 like this:
$ cd /vagrant
$ python3.6 -m venv djangoapp
Why do we need pyenv/virtualenv?

If this doesn't work and can't create the folder, stop virtual machine (vagrant halt) and run CMD and Teraterm as an administrator. Then try these commands again.

Start the virtual environment of pyenv:
$ source ./djangoapp/bin/activate
If you want to stop the virtual environment:
$ deactivate
But you don't need to stop it yet.
Update pip of the virtual environment if necessary:
$ python3.6 -m pip install --upgrade pip

Because we are in the virtual environment, the python and pip of virtual environement will be used:
$ python --version
Python 3.6.7
$ which python
/vagrant/djangoapp/bin/python
$ pip --version
pip 9.0.1 from /vagrant/djangoapp/lib64/python3.6/site-packages (python 3.6)


Sign in to mysql and create a table:
$ mysql -u root -proot
mysql> CREATE DATABASE testdb CHARACTER SET utf8;
mysql> exit

Then install nginx (web server software) and remove Apache (also web server software):
$ sudo yum remove -y httpd
$ sudo yum autoremove
$ sudo rpm -Uvh https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
$ sudo yum install -y nginx
$ sudo systemctl start nginx
$ sudo systemctl enable nginx

Go to "http://192.168.33.10/" and check if nginx is working correctly.


The configuration file of nginx is here: /etc/nginx/nginx.conf
$ less /etc/nginx/nginx.conf

Install the Django framework:
$ python3.6 -m pip install django

The files to serve of nginx are here: /usr/share/nginx/html
$ ls /usr/share/nginx/html

You can see the configuration in nginx.conf:
$ vi /etc/nginx/nginx.conf

here 

And Install uwsgi (WSGI: Web Server Gateway Interface):
$ python3.6 -m pip install uwsgi


Django framework


Create a project of Django:
$ cd /vagrant/djangoapp
$ django-admin startproject mypj

After doing these commands, you will get a project folder of Django in this directory: /vagrant/djangoapp. The name of the project folder is "mypj". And in the mypj folder, you will find that there is another mypj folder there.


In the folder....



Open the file "setting.py" that is in the folder "mypj".


Add "localhost" and "192.168.33.10" to "Allowed_Hosts" like this:
ALLOWED_HOSTS = ['localhost','192.168.33.10']
(Assuming that your virtual server's IP address is "192.168.33.10")


Run this command and start the built-in server of Django:
$ python mypj/manage.py runserver 0.0.0:8000

Go to the URL: http://192.168.33.10:8000/



If this is displayed, it means you successfully installed Django :)

Hello World


Now we stop the built-in server with ctrl+c.

Go to the mypj directory on the console.
$ cd ./mypj

There is manage,py at this directory of django

We will create a top-level module in this directory.
$ python3.6 manage.py startapp mywebsite

mywebsite directory is created

In the mywebsite directory, you can see that these files are there:


Open the view.py and write as follows:
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world Django!!!!")

Create a file called "urls.py".



Write as follows in urls.py:
from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'),
]

Now go back to djangoapp/mypj/mypj (the submodule of mypj) and open urls.py.
Import "include" and add this path.
from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('mywebsite/', include('mywebsite.urls')),
    path('admin/', admin.site.urls),
]

Run the server.
$ cd /vagrant/djangoapp/mypj
$ python3.6 manage.py runserver 0.0.0:8000

Go to http://192.168.33.10:8000/mywebsite/ and you will see the message you defined in index function.

Check if uWSGI can connect to Django


Check if uWSGI can connect to Django by the following command:
$ cd /vagrant/djangoapp/mypj
$ uwsgi --http :8000 --module mypj.wsgi

Go to http://192.168.33.10:8000/mywebsite/ and see if your Hello Django message properly.
After checking if it works, ctrl + c to stop uwsgi.