891rpm

Установка Redmine 4.0.5 NGINX PostgreSQL в Centos 7

Redmine — открытое серверное веб-приложение для управления проектами и задачами (в том числе для отслеживания ошибок). Redmine написан на Ruby и представляет собой приложение на основе широко известного веб-фреймворка Ruby on Rails

Подготовительный этап

Устанавливаем пакеты, необходимые для сборки Redmine и Ruby из исходного кода

$ sudo yum install nano curl gpg gcc gcc-c++ make patch autoconf automake bison libffi-devel libtool libcurl-devel
$ sudo yum install readline-devel sqlite-devel zlib-devel openssl-devel readline  glibc-headers glibc-devel
$ sudo yum install zlib libyaml-devel bzip2 iconv-devel ImageMagick ImageMagick-devel gdbm-devel  mariadb-devel

Создадим нового пользователя, добавляем его в группу Wheel

$ sudo useradd -m -U -r -d /opt/redmine redmine
$ sudo usermod -aG wheel redmine
$ sudo chmod 750 /opt/redmine

Разрешаем пользователю redmine делать sudo, не запрашивая пароль

$ echo "redmine ALL=(ALL) NOPASSWD: ALL" | sudo tee -a /etc/sudoers.d/redmine > /dev/null

Добавляем правила в Firewall

$ sudo firewall-cmd --permanent --zone=public --add-service=http
$ sudo firewall-cmd --permanent --zone=public --add-service=https 
$ sudo firewall-cmd --reload
$ sudo firewall-cmd --list-all-zones

Установка и настройка PostgreSQL 10

Добавляем репозиторий

$ sudo yum install https://download.postgresql.org/pub/repos/yum/reporpms/EL-7-x86_64/pgdg-redhat-repo-latest.noarch.rpm

Устанавливаем PostgreSQL

$ sudo yum install libpqxx libpqxx-devel postgresql10.x86_64 postgresql10-server postgresql10-contrib postgresql10-libs postgresql10-tcl postgresql10-devel protobuf-devel

Инициализируем пространство для БД

$ sudo /usr/pgsql-10/bin/postgresql-10-setup initdb

Добавляем службу в автозагрузку и запускаем PostgreSQL

$ sudo systemctl start postgresql-10
$ sudo systemctl enable postgresql-10

Переключаемся на пользователя postgres

$ sudo su - postgres

Создаем пользователя БД

-bash-4.2$ createuser redmine

Переключаемся в PostgreSQL shell

-bash-4.2$ psql

Задаем пароль для пользователя БД

postgres=# ALTER USER redmine WITH ENCRYPTED password '%passwd%';

Создам базу и задаем владельца базы

postgres=# CREATE DATABASE redmine WITH ENCODING='UTF8' OWNER=redmine;
Exit
\q
logout

Настраиваем доступ к PostgreSQL

$ sudo nano /var/lib/pgsql/10/data/pg_hba.conf
# TYPE  DATABASE        USER            ADDRESS                 METHOD

# "local" is for Unix domain socket connections only
local   all             all                                     trust
# IPv4 local connections:
host    all             all             127.0.0.1/32            md5
# IPv6 local connections:
host    all             all             ::1/128                 md5

Перезапускаем PostgreSQL

$ sudo systemctl restart postgresql-10

Установка Ruby из исходников

Переключаемся на пользователя redmine

$ sudo su - redmine

Скачиваем ruby 2.6.5, собираем из исходников

$ curl -L https://cache.ruby-lang.org/pub/ruby/2.6/ruby-2.6.5.tar.gz -o /tmp/ruby-2.6.5.tar.gz 
$ cd /tmp
$ tar zxf /tmp/ruby-2.6.5.tar.gz
$ sudo mv /tmp/ruby-2.6.5 /opt/ruby
$ sudo chown -R redmine. /opt/ruby
$ cd /opt/ruby
$ ./configure --disable-install-doc
$ make -j2
$ sudo make install

Что бы удалить собранный из исходников ruby:

$ sudo make clean

Проверяем

$ ruby -v
ruby 2.6.5p114 (2019-10-01 revision 67812) [x86_64-linux]

Установка Rubygems из исходников

Скачиваем rubygems 3.0.6, собираем из исходников

$ curl -L https://rubygems.org/rubygems/rubygems-3.0.6.tgz -o /tmp/rubygems-3.0.6.tgz
$ cd /tmp
$ tar -zxf rubygems-3.0.6.tgz
$ cd rubygems-3.0.6
$ sudo chown -R redmine. /usr/local/lib/ruby/
$ alias sudo='sudo env PATH=$PATH'
$ sudo ruby setup.rb

Проверяем

$ gem -v
3.0.6

Устанавливаем Redmine. Начало

Скачиваем и распаковываем redmine

$ cd /tmp
$ curl -L http://www.redmine.org/releases/redmine-4.0.5.tar.gz -o /tmp/redmine-4.0.5.tar.gz
$ tar zxf /tmp/redmine-4.0.5.tar.gz
$ sudo mv /tmp/redmine-4.0.5 /opt/redmine/redmine-4.0.5

Создаем симлинк

$ sudo ln -s /opt/redmine/redmine-4.0.5 /opt/redmine/redmine-latest
$ sudo chown -h redmine:redmine /opt/redmine/redmine-latest

Настраиваем подключение к PostgreSQL

$ cp /opt/redmine/redmine-4.0.5/config/database.yml.example /opt/redmine/redmine-4.0.5/config/database.yml
$ nano /opt/redmine/redmine-4.0.5/config/database.yml

production:
  adapter: postgresql
  database: redmine
  host: localhost
  username: redmine
  password: "%passwd%"
  encoding: utf8

Устанавливаем Redmine (если сервер имеет выход в интернет)

$ alias sudo='sudo env PATH=$PATH'
$ cd /opt/redmine/redmine-4.0.5
$ sudo gem install bundler

Если сервер не имеет выход в интернет, надо скачать необходимые пакеты (gem)

gem "bundler", ">= 1.5.0" https://rubygems.org/downloads/bundler-2.0.2.gem
gem "rails", "5.2.3" https://rubygems.org/downloads/rails-5.2.3.gem
gem "rouge", "~> 3.3.0" https://rubygems.org/downloads/rouge-3.3.0.gem
gem "request_store", "1.0.5" https://rubygems.org/downloads/request_store-1.0.5.gem
gem "mini_mime", "~> 1.0.1" https://rubygems.org/downloads/mini_mime-1.0.1.gem
gem "actionpack-xml_parser" https://rubygems.org/downloads/actionpack-xml_parser-2.0.1.gem
gem "roadie-rails", "~> 1.3.0" https://rubygems.org/downloads/roadie-rails-1.3.0.gem
gem "mimemagic" https://rubygems.org/downloads/mimemagic-0.3.3.gem
gem "mail", "~> 2.7.1" https://rubygems.org/downloads/mail-2.7.1.gem
gem "csv", "~> 3.0.1" if RUBY_VERSION >= "2.3" && RUBY_VERSION < "2.6" https://rubygems.org/downloads/csv-3.1.0.gem
gem "nokogiri", (RUBY_VERSION >= "2.3" ? "~> 1.10.0" : "~> 1.9.1") https://rubygems.org/downloads/nokogiri-1.10.5.gem
gem "i18n", "~> 0.7.0" https://rubygems.org/downloads/i18n-0.7.0.gem
gem "xpath", "< 3.2.0" if RUBY_VERSION < "2.3" https://rubygems.org/downloads/xpath-3.2.0.gem
gem "sprockets", "~> 3.7.2" https://rubygems.org/downloads/sprockets-3.7.2.gem
gem 'tzinfo-data', platforms: [:mingw, :x64_mingw, :mswin] https://rubygems.org/downloads/tzinfo-data-1.2019.3.gem
gem "rbpdf", "~> 1.19.6" https://rubygems.org/downloads/rbpdf-1.20.1.gem
gem "net-ldap", "~> 0.16.0" https://rubygems.org/downloads/net-ldap-0.16.1.gem
gem "ruby-openid", "~> 2.9.2", :require => "openid" https://rubygems.org/downloads/ruby-openid-2.9.2.gem
gem "rack-openid" https://rubygems.org/downloads/rack-openid-1.4.2.gem
gem "rmagick", "~> 2.16.0" https://rubygems.org/downloads/rmagick-2.16.0.gem
gem "redcarpet", "~> 3.4.0" https://rubygems.org/downloads/redcarpet-3.4.0.gem
gem "pg", "~> 1.1.4", :platforms => [:mri, :mingw, :x64_mingw] https://rubygems.org/downloads/pg-1.1.4.gem
gem 'mini_portile2' (~> 2.4.0)  https://rubygems.org/downloads/mini_portile2-2.4.0.gem
gem 'tzinfo' (>= 1.0.0) https://rubygems.org/downloads/tzinfo-2.0.0.gem
gem 'concurrent-ruby' (~> 1.0) https://rubygems.org/downloads/concurrent-ruby-1.0.5.gem
gem 'sprockets-rails' (>= 2.0.0) https://rubygems.org/downloads/sprockets-rails-3.2.1.gem
#gem 'railties' (= 6.0.1) https://rubygems.org/downloads/railties-6.0.1.gem
#gem 'actiontext' (= 6.0.1) https://rubygems.org/downloads/actiontext-6.0.1.gem
#gem 'actionmailbox' (= 6.0.1) https://rubygems.org/downloads/actionmailbox-6.0.1.gem
#gem 'activestorage' (= 6.0.1) https://rubygems.org/downloads/activestorage-6.0.1.gem
#gem 'actioncable' (= 6.0.1) https://rubygems.org/downloads/actioncable-6.0.1.gem
#gem 'activejob' (= 6.0.1) https://rubygems.org/downloads/activejob-6.0.1.gem
#gem 'actionmailer' (= 6.0.1) https://rubygems.org/downloads/actionmailer-6.0.1.gem
#gem 'activerecord' (= 6.0.1) https://rubygems.org/downloads/activerecord-6.0.1.gem
#gem 'activemodel' (= 6.0.1) https://rubygems.org/downloads/activemodel-6.0.1.gem
#gem 'actionview' (= 6.0.1) https://rubygems.org/downloads/actionview-6.0.1.gem
#gem 'actionpack' (= 6.0.1) https://rubygems.org/downloads/actionpack-6.0.1.gem
#gem 'activesupport' (= 6.0.1) https://rubygems.org/downloads/activesupport-6.0.1.gem
gem 'method_source' (>= 0) https://rubygems.org/downloads/method_source-0.9.2.gem
gem 'thor' (>= 0.20.3, < 2.0) https://rubygems.org/downloads/thor-0.20.3.gem
gem 'marcel' (~> 0.3.1) https://rubygems.org/downloads/marcel-0.3.1.gem
gem 'websocket-driver' (>= 0.6.1) https://rubygems.org/downloads/websocket-driver-0.7.1.gem
gem 'nio4r' (~> 2.0) https://rubygems.org/downloads/nio4r-2.0.0.gem
gem 'globalid' (>= 0.3.6) https://rubygems.org/downloads/globalid-0.4.2.gem
gem 'rails-dom-testing' (~> 2.0) https://rubygems.org/downloads/rails-dom-testing-2.0.3.gem
gem 'rails-html-sanitizer' (~> 1.1, >= 1.2.0) https://rubygems.org/downloads/rails-html-sanitizer-1.3.0.gem
gem 'erubi' (~> 1.4) https://rubygems.org/downloads/erubi-1.4.0.gem
gem 'builder' (~> 3.1) https://rubygems.org/downloads/builder-3.1.4.gem
gem 'rack-test' (>= 0.6.3) https://rubygems.org/downloads/rack-test-1.1.0.gem
gem 'zeitwerk' (~> 2.2) https://rubygems.org/downloads/zeitwerk-2.2.1.gem
gem 'tzinfo' (~> 1.1) https://rubygems.org/downloads/tzinfo-1.1.0.gem
gem 'websocket-extensions' (>= 0.1.0) https://rubygems.org/downloads/websocket-extensions-0.1.4.gem
gem 'loofah' (~> 2.3) https://rubygems.org/downloads/loofah-2.3.1.gem
gem 'crass' (~> 1.0.2) https://rubygems.org/downloads/crass-1.0.5.gem
gem 'thread_safe' (~> 0.1) https://rubygems.org/downloads/thread_safe-0.1.3.gem
gem 'atomic' (>= 0) https://rubygems.org/downloads/atomic-1.1.101.gem
gem 'railties' (= 5.2.3) https://rubygems.org/downloads/railties-5.2.3.gem
gem 'actiontext' (= 5.2.3) https://rubygems.org/downloads/actiontext-5.2.3.gem
gem 'actionmailbox' (= 5.2.3) https://rubygems.org/downloads/actionmailbox-5.2.3.gem
gem 'activestorage' (= 5.2.3) https://rubygems.org/downloads/activestorage-5.2.3.gem
gem 'actioncable' (= 5.2.3) https://rubygems.org/downloads/actioncable-5.2.3.gem
gem 'activejob' (= 5.2.3) https://rubygems.org/downloads/activejob-5.2.3.gem
gem 'actionmailer' (= 5.2.3) https://rubygems.org/downloads/actionmailer-5.2.3.gem
gem 'activerecord' (= 5.2.3) https://rubygems.org/downloads/activerecord-5.2.3.gem
gem 'activemodel' (= 5.2.3) https://rubygems.org/downloads/activemodel-5.2.3.gem
gem 'actionview' (= 5.2.3) https://rubygems.org/downloads/actionview-5.2.3.gem
gem 'actionpack' (= 5.2.3) https://rubygems.org/downloads/actionpack-5.2.3.gem
gem 'activesupport' (= 5.2.3) https://rubygems.org/downloads/activesupport-5.2.3.gem
gem 'arel' (>= 9.0) https://rubygems.org/downloads/arel-9.0.0.gem
gem 'minitest' (~> 5.1) https://rubygems.org/downloads/minitest-5.1.0.gem
gem 'roadie' (~> 3.1) https://rubygems.org/downloads/roadie-3.1.1.gem
gem 'css_parser' (~> 1.3.4) https://rubygems.org/downloads/css_parser-1.3.4.gem
gem 'nokogiri' (>= 1.5.0, < 1.7.0) https://rubygems.org/downloads/nokogiri-1.6.8.1.gem
gem 'addressable' (>= 0) https://rubygems.org/downloads/addressable-2.7.0.gem
gem 'public_suffix' (>= 2.0.2, < 5.0) https://rubygems.org/downloads/public_suffix-4.0.1.gem
gem 'mini_portile2' (~> 2.1.0) https://rubygems.org/downloads/mini_portile2-2.1.0.gem
gem 'sprockets' (~> 3.7.2 ) https://rubygems.org/downloads/sprockets-3.7.2.gem
gem 'rbpdf (~> 1.19.6)' https://rubygems.org/downloads/rbpdf-1.19.8.gem
gem 'rbpdf-font' (~> 1.19.0) https://rubygems.org/downloads/rbpdf-font-1.19.1.gem
gem 'htmlentities' (>= 0) https://rubygems.org/downloads/htmlentities-4.3.4.gem
gem 'mysql2 (~> 0.5.0)' https://rubygems.org/downloads/mysql2-0.5.2.gem
gem 'yard' https://rubygems.org/downloads/yard-0.9.20.gem
gem 'mocha' https://rubygems.org/downloads/mocha-1.9.0.gem
gem 'metaclass' (~> 0.0.1) https://rubygems.org/downloads/metaclass-0.0.4.gem
gem 'simplecov (~> 0.14.1)' https://rubygems.org/downloads/simplecov-0.14.1.gem
gem 'docile' (~> 1.1.0) https://rubygems.org/downloads/docile-1.1.5.gem
gem 'simplecov-html' (~> 0.10.0) https://rubygems.org/downloads/simplecov-html-0.10.2.gem
gem 'puma (~> 3.7)' https://rubygems.org/downloads/puma-3.7.1.gem
gem 'capybara (~> 2.13)' https://rubygems.org/downloads/capybara-2.13.0.gem
gem 'xpath' (~> 2.0) https://rubygems.org/downloads/xpath-2.0.0.gem
gem 'mime-types' (>= 1.16) https://rubygems.org/downloads/mime-types-3.3.gem
gem 'mime-types-data' (~> 3.2015) https://rubygems.org/downloads/mime-types-data-3.2015.1120.gem
gem 'selenium-webdriver' https://rubygems.org/downloads/selenium-webdriver-3.142.6.gem
gem 'rubyzip' (>= 1.2.2) https://rubygems.org/downloads/rubyzip-1.3.0.gem
gem 'childprocess' (>= 0.5, < 4.0) https://rubygems.org/downloads/childprocess-3.0.0.gem
gem 'rake (>= 0.8.7)' https://rubygems.org/downloads/rake-13.0.1.gem

Положить их в каталог /opt/redmine/redmine-4.0.5/vendor/cache

И установить bundler и passenger локально

$ cd /opt/redmine/redmine-4.0.5/vendor/cache
$ sudo gem install bundler --local
$ sudo gem install passenger --local

Установка NGINX + Passenger

Скачиваем NGINX и устанавливаем его с поддержкой Passenger

$ cd /tmp
$ curl -L https://nginx.org/download/nginx-1.17.5.tar.gz -o /tmp/nginx-1.17.5.tar.gz
$ tar zxf /tmp/nginx-1.17.5.tar.gz
$ sudo passenger-install-nginx-module --prefix=/opt/nginx --nginx-source-dir=/tmp/nginx-1.17.5 --languages ruby
Enter your choice (1 or 2) or press Ctrl-C to abort: 2 (собираем из исходников)
Please specify the directory: /tmp/nginx-1.17.5
Please specify a prefix directory [/opt/nginx]:

--------------------------------------------

Nginx with Passenger support was successfully installed.

The Nginx configuration file (/opt/nginx/conf/nginx.conf)
must contain the correct configuration options in order for Phusion Passenger
to function correctly.

This installer has already modified the configuration file for you! The
following configuration snippet was inserted:

  http {
      ...
      passenger_root /usr/local/lib/ruby/gems/2.6.0/gems/passenger-6.0.4;
      passenger_ruby /usr/local/bin/ruby;
      ...
  }

After you start Nginx, you are ready to deploy any number of Ruby on Rails
applications on Nginx.

Press ENTER to continue.

-------------------------------------------------

Для удобства создаём симлинк

$ sudo ln -s /opt/nginx/conf/ /etc/nginx

Редактируем файл конфигурации Nginx:

$ sudo nano /opt/nginx/conf/nginx.conf
user redmine;
worker_processes  auto;
...

В блок http добавляем следующий текст (в самом низу)

...
include sites-enabled/*.conf;
server_names_hash_bucket_size 64;
}

Далее настраиваем доступ к хосту Redmine

$ sudo mkdir /opt/nginx/conf/{sites-available,sites-enabled}
$ sudo nano /opt/nginx/conf/sites-available/redmine.conf

Пример конфигурационного файла для nginx

$ cat redmine.conf
server {
    listen 80 default_server;
    server_name redmine.example.com;

    gzip on;
    gzip_comp_level 7;
    gzip_types application/x-javascript application/javascript text/css;

    set $root_path /opt/redmine/redmine-latest/public;
    root $root_path;

    passenger_enabled on;
    passenger_document_root $root_path;
    client_max_body_size      100m; # Max attachemnt size
    client_body_buffer_size 4M;

    # redirect server error pages to the static page /50x.html
    error_page   500 502 503 504  /50x.html;

    location = /50x.html {
        root   html;
    }
		
    location ~* \.(jpg|gif|png|js|css|ico)$ {
        root $root_path;
        expires 7d;
    }

}

Делаем симлинк

$ cd /opt/nginx/conf/sites-available
$ sudo ln -s /opt/nginx/conf/sites-available/redmine.conf /opt/nginx/conf/sites-enabled/redmine.conf

Проверяем nginx

$ sudo /opt/nginx/sbin/nginx -t

Создаем файл для запуска nginx в качестве сервиса

$ sudo nano /lib/systemd/system/nginx.service
[Unit]
Description=The NGINX HTTP and reverse proxy server
After=syslog.target network.target remote-fs.target nss-lookup.target
 
[Service]
Type=forking
PIDFile=/opt/nginx/logs/nginx.pid
ExecStartPre=/opt/nginx/sbin/nginx -t
ExecStart=/opt/nginx/sbin/nginx
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true
 
[Install]
WantedBy=multi-user.target

Перечитываем конфигурации systemd

$ sudo systemctl daemon-reload

Запускаем Nginx и добавляем его в автозагрузку

$ sudo systemctl start nginx
$ sudo systemctl enable nginx

Устанавливаем Redmine. Продолжение

Переходим в каталог

$ cd /opt/redmine/redmine-4.0.5/

Прописываем настройки для PostgreSQL

$ bundle config build.pg --with-pg-config=/usr/pgsql-10/bin/pg_config

Устанавливаем необходимые gems (локальная установка)

$ bundle install --without development test mysql2 sqlite --local

Либо, если у сервера есть выход в интернет, устанавливаем необходимые gems:

$ bundle install --without development test mysql2 sqlite

Запускаем генерацию токена:

$ bundle exec rake generate_secret_token

Создаем структуру БД

$ RAILS_ENV=production bundle exec rake db:migrate

Загружаем в базу дефолтные данные

$ RAILS_ENV=production bundle exec rake redmine:load_default_data
  Select language: ru

Установка приложения Redmine завершена. Меняем владельца и прав доступа к каталогам и файлам

$ mkdir -p tmp tmp/pdf public/plugin_assets
$ chown -R redmine:redmine files log tmp public/plugin_assets
$ chmod -R 755 files log tmp public/plugin_assets

Перезагружаем nginx

$ sudo systemctl restart nginx

Осталось поменять пароль админа, для этого открываем браузер, переходим на соответствующую страницу и меняем пароль

Настройка LDAP AD / FreeIPA

Настройка параметров LDAP производится через web-интерфейс

Пример параметров для подключения LDAP Active Directory

Имя: example.com
Компьютер: 192.168.0.2
Порт: 389 LDAP
Учётная запись: user@example.com
Пароль: •••••••••••••••
BaseDN: dc=example,dc=com
Создание пользователя на лету
Атрибут Login: sAMAccountName
Имя: givenName
Фамилия: sn
email: mail

Пример параметров для подключения LDAP FreeIPA

Имя: FreeIPA
Компьютер: freeipa.example.com
Порт: 636 LDAPS без проверки сертификата
Учётная запись
Пароль
BaseDN: cn=accounts,dc=example,dc=com
Создание пользователя на лету
Атрибут Login: uid
Имя: givenName
Фамилия: sn
email: mail

 

 

Установка Redmine 4.0.5 NGINX PostgreSQL в Centos 7

Deploy Django, Gunicorn, NGINX, PostgresQL using Docker

This post mainly based on this blog: https://docs.docker.com/compose/django/.I will be extending this post by serving django+gunicorn using Nginx, also I will using Postgresql docker container to use it as database.

Lets not waste time and go to the following steps.

1. Let’s make an empty directory named myproject and add another folder inside name it srcsrc should contain the django project. For testing purpose lets put a simple django project inside named mydjango.

2. Let’s create a subdirectory inside myproject and name it config. Lets put a requirement.pip file inside config and write these line in it:

Django==1.10  
gunicorn==19.6.0  
psycopg2==2.6.2

3. Now let’s make a Dockerfile inside the myproject. This should contain the following lines:

FROM python:3.5  
ENV PYTHONUNBUFFERED 1  
RUN mkdir /config  
ADD /config/requirements.pip /config/  
RUN pip install -r /config/requirements.pip  
RUN mkdir /src;  
WORKDIR /src
So this Dockerfile starts with a Python 3.5 based image. Then the container is modified by adding the requirement.pip file in /config directory within the container and installing the packages from it.4. Let’s create a file called docker-compose.yml in myproject directory.

The docker-compose.yml file describes the services that make your app. Here we need a web service(Django+Gunicorn), A database(Postgres), and Proxy Server(Nginx). It also describes which Docker images these services will use, how they will link together, any volumes they might need mounted inside the containers. Finally, the docker-compose.yml file describes which ports these services expose. See the docker-compose.yml reference for more information on how this file works. Don’t forget to add docker-compose
to your python environment by running pip install docker-compose.

5. Let’s add the following configuration to the docker-compose.yml file:

version: '2'  
services:  
  nginx:
    image: nginx:latest
    container_name: ng01
    ports:
      - "8000:8000"
    volumes:
      - ./src:/src
      - ./config/nginx:/etc/nginx/conf.d
    depends_on:
      - web
  web:
    build: .
    container_name: dg01
    command: bash -c "python manage.py makemigrations && python manage.py migrate && gunicorn mydjango.wsgi -b 0.0.0.0:8000"
    depends_on:
      - db
    volumes:
      - ./src:/src
    expose:
      - "8000"

  db:
    image: postgres:latest
    container_name: ps01
It says that there are three services for this project: nginx, web, db. nginx depends on web, web depends on db. db container uses postgres’s latest image from dockerhub. Default username for db is postgres and password is postgres
web container is build using project’s Dockerfile. It mounts src directory into it and exposes port 8000. version is being used for which format to use to compose the docker file.nginx uses nginx’s latest image from dockerhub. This proxy server is accessible from port 8000. It mounts src and config directory.

6. Now let’s write a nginx configuration config file named mydjango.conf inside myproject‘s config folder and put it in a subdirectory named nginx.

upstream web {  
  ip_hash;
  server web:8000;
}

# portal
server {  
  location / {
        proxy_pass http://web/;
    }
  listen 8000;
  server_name localhost;
}
So what it does that, nginx acts as a reverse proxy for any connections going to django server and all connections goes through nginx to reach django server.Project Directory should look like this:

── myproject
    ├── src
    │   ├── mydjango
    │   ├── manage.py
    ├── config
    │   ├── requirements.pip
    │   ├── nginx
    │      ├── mydjango.conf
    ├── Dockerfile
    └── docker-compose.yml
7. To communicate from django to postgres, we need to put database configuration in django applications settings file. It should look like this:
DATABASES = {  
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'postgres',
        'USER': 'postgres',
        'HOST': 'db',
        'PORT': 5432,
    }
}

8. All is done. Now lets run docker-compose build in terminal within the project directory. It will build/rebuild(if necessary) all the containers. For first time running the containers, run docker-compose up -d. Lets go to browser and type: localhost:8000. We should see the django application up and running.

9. For stopping the docker, run docker-compose stop. Re-running docker, use docker-compose start.10. For shell accessing.

#Nginx
docker exec -ti nginx bash

#Web
docker exec -ti web bash

#Database
docker exec -ti db bash
For logs:
#Nginx
docker-compose logs nginx
#Web
docker-compose logs web
#DB
docker-compose logs db
Thats it. You can see an working example here in my repo: https://github.com/ruddra/docker-djangoAlso another deployment example for Ruby on rails here: https://github.com/ruddra/deploy-notebook
(Thanks to Akimul Islam for the source)

Cheers!!

Update:

Serving django with gunicorn won’t allow you to serve static files with it. You need to serve static files seperately. You can follow this post: http://ruddra.com/2016/11/02/serve-static-files-by-nginx-from-django-using-docker/ for how to do serve static files using Nginx from docker.

 

How to Install and Connect to PostgreSQL on CentOS 7

postgresqlPostgreSQL (pronounced ‘post-gres-Q-L’) is a free, open-source object-relational database management system (object-RDBMS), similar to MySQL, and is standards-compliant and extensible. It is commonly used as a back-end for web and mobile applications. PostgreSQL, or ‘Postgres’ as it is nicknamed, adopts the ANSI/ISO SQL standards together, with the revisions.

Pre-Flight Check
  • These instructions are intended specifically for installing PostgreSQL on CentOS 7.
  • I’ll be working from a Liquid Web Self Managed CentOS 7 server, and I’ll be logged in as root.
Step 1: Add the PostgreSQL 9.3 Repository

In this case we want to install PostgreSQL 9.3 directly from the Postgres repository. Let’s add that repo:

wget http://yum.postgresql.org/9.4/redhat/rhel-7-x86_64/pgdg-centos94-9.4-1.noarch.rpm
rpm -ihvU pgdg-centos94-9.4-1.noarch.rpm

Step 2: Install PostgreSQL

First, you’ll follow a simple best practice: ensuring the list of available packages is up to date before installing anything new.

yum -y update

Then it’s a matter of just running one command for installation via apt-get:

yum -y install postgresql94 postgresql94-server postgresql94-contrib postgresql94-libs --disablerepo=* --enablerepo=pgdg94

PostgreSQL should now be installed.

Step 3: Start PostgreSQL

Configure Postgres to start when the server boots:

systemctl enable postgresql-9.4

Start Postgres:

/usr/pgsql-9.4/bin/postgresql94-setup initdb

systemctl start postgresql-9.4

Step 4: Switch to the Default PostgreSQL User

As part of the installation Postgres adds the system user postgres and is setup to use “ident” authentication. Rolesinternal to Postgres (which are similar to users) match with a system user account.

Let’s switch into that system user:

su – postgres

And then connect to the PostgreSQL terminal (in the postgres role):

$ psql

That’s it! You’re connected and ready to run commands in PostgreSQL as the postgres role.

Synology NAS: Run Fsck To Check and Repair a Linux File System

DS509+I own a Linux powered Synology dedicated Network Attached Storage (NAS) server for my home office use. How do I run fsck on Synology DiskStation that offers RAID storage using Linux command line options over an ssh session?

This server is powered by Linux operating system and comes with the e2fsck program that can be used to check the ext3/ext4 family of file systems.

Difficulty: Intermediate
Root privileges: Yes
Requirements: Synology server

First, you need to login using ssh interface. The syntax is as follows:

ssh root@nas01
ssh root@nas-server-ip-here

Once logged in you need to stop running services such as smb/nfs/pgsql and so. To see current volumes or mount point type the following command:

df

Sample outputs:

Filesystem           1K-blocks      Used Available Use% Mounted on
rootfs                 2451064    437412   1911252  19% /
/dev/root              2451064    437412   1911252  19% /
/tmp                    255700       272    255428   1% /tmp
/dev/vg1/volume_1    2879621632 176443652 2703075580   7% /volume1
/dev/vg1/volume_1    2879621632 176443652 2703075580   7% /opt

To see current services accessing the /volume1/ and /opt/, run:

lsof /opt/
lsof /volume1/

Sample outputs:

COMMAND   PID  USER   FD   TYPE DEVICE SIZE/OFF    NODE NAME
postgres 5052 admin  cwd    DIR  253,0     4096      18 /volume1/@database/pgsql
postgres 5057 admin  cwd    DIR  253,0     4096      18 /volume1/@database/pgsql
postgres 5057 admin   17u   REG  253,0 16777216 3539006 /volume1/@database/pgsql/pg_xlog/000000010000000000000006
postgres 5058 admin  cwd    DIR  253,0     4096      18 /volume1/@database/pgsql
lsof     8284  root  txt    REG  253,0   125544 4068473 /opt/sbin/lsof
lsof     8285  root  txt    REG  253,0   125544 4068473 /opt/sbin/lsof

You need to stop pgsql service, enter:

/usr/syno/etc/rc.d/S20pgsql.sh stop

Sample outputs:

Stopping PostgreSQL...

In short, you need to stop services that are running and accessing data shares such as SMB,NFS,pgsql,mysql and so on. You can use web interface to stop these services too. cd to /usr/syno/etc/rc.d/ and stop all file sharing services. Finally, unmount volumes as follows:

umount /volume1/
umount /opt

Verify that /opt and /volume1/ are unmounted:

df

Sample outputs:

Filesystem           1K-blocks      Used Available Use% Mounted on
/dev/md0               2451064    437408   1911256  19% /
/tmp                    255700       264    255436   0% /tmp

Run fsck on ext4 file system:

fsck.ext4 -v /dev/vg1/volume_1

OR

e2fsck -p -y -f -v /dev/vg1/volume_1

Sample outputs:

e2fsck 1.41.12 (17-May-2010)
1.41.12-2198: is cleanly umounted, 474816/182845440 files, 55587266/731381760 blocks
 (check after next mount)

Reboot the server:

reboot