Архив рубрики: bd

service mongodb in Ubuntu 16

link

So I had to write one from scratch. To create one of your own follow these steps:

  1. switch to root using
    sudo su
    

or use sudo for all the following steps.

  1. create a service script (in this example the name of the service is Mongodb)
    nano /lib/systemd/system/mongodb.service
    
  2. File content should be
    [Unit]
    Description=MongoDB Database Service
    Wants=network.target
    After=network.target
    
    [Service]
    ExecStart=/usr/bin/mongod --config /etc/mongod.conf
    ExecReload=/bin/kill -HUP $MAINPID
    Restart=always
    User=mongodb
    Group=mongodb
    StandardOutput=syslog
    StandardError=syslog
    
    [Install]
    WantedBy=multi-user.target
    

You can also download the file from here: mongodb.service
Here is a quick description of the important fields:
ExecStart - Is the command to run. Mongo installs itself under /usr/bin and the configuration file is written at /etc
User - The uid of the mongod process.
Group - The gid of the mongod process. Note that the user and group are created by the installation.

Now to start mongodb:

sudo systemctl start mongodb

To stop mongodb service use:

sudo systemctl stop mongodb

To enable mongodb on startup

sudo systemctl enable mongodb.service

If you need to refresh the services use:

 sudo systemctl daemon-reload

 

redis install

wget http://rpms.famillecollet.com/enterprise/6/remi/x86_64/remi-release-6.9-2.el6.remi.noarch.rpm
rpm -Uvh http://epel.mirror.net.in/epel/6/x86_64/epel-release-6-8.noarch.rpm
rpm -Uvh remi-release-6.9-2.el6.remi.noarch.rpm
yum --enablerepo=remi install redis
chkconfig redis on
/sbin/service redis start
telnet 127.0.0.1 6379
set attitude:today "happy"
get attitude:today

create database

link

I always forget the MySQL create database with UTF8 character set syntax, so here it is:

CREATE DATABASE `mydb` CHARACTER SET utf8 COLLATE utf8_general_ci;
GRANTALLON`mydb`.*TO`username`@localhost IDENTIFIED BY 'password';

Alternatively, you can use ‘CREATE SCHEMA’ instead of ‘CREATE DATABASE’:

CREATESCHEMA`mydb` CHARACTER SET utf8 COLLATE utf8_general_ci;
GRANTALLON`mydb`.*TO`username`@localhost IDENTIFIED BY 'password';

how to fix phpMyAdmin session error

phpMyAdmin is great free web based PHP software to manage databases, tables, fields, users… and more. phpMyAdmin support MySQL, MariaDB, and Drizzle with the ability to execute SQL statements.

Unfortunately sometimes I get problem with phpMyAdmin, here is the error from phpMyAdmin on my centos Linux Server

phpMyAdmin – Error

To test and find out where is session.save path
http://wiki.phpmyadmin.net/pma/session.save_path

run this script on your web server

Here is the output i have

If the folder doesn’t exist, create one.

 

You may have to change ownership of the directly

 

 

Or just need to change the permissions to readable and writable for the directory

 

 

Note: /var/lib/php/session ownership and permissions well reverse back to root and not writable after a reboot. It’s a good idea to run chmod and chown @reboot so you don’t have to do it manually.

add this to your crontab

with the content (replace user:group to user/group which running apache/nginx web server)

mysql workbanch remotly

CREATEUSER'username'@'localhost' IDENTIFIED BY'password';
GRANTALL PRIVILEGES ON*.*TO'username'@'localhost'WITHGRANTOPTION;
CREATEUSER'username'@'%' IDENTIFIED BY'password';
GRANTALL PRIVILEGES ON*.*TO'username'@'%'WITHGRANTOPTION;
FLUSH PRIVILEGES;

mysql utf8

 

CREATE DATABASE dbname CHARACTER SET utf8 COLLATE utf8_general_ci;
ALTER SCHEMA database DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci;
ALTER TABLE table_name CHARACTER SET utf8 COLLATE utf8_unicode_ci;
ALTER TABLE mytable CONVERTTO CHARACTER SET utf8;
show table status;

How to install MySQL Server 5.6 on CentOS 7 / RHEL 7

How to install MySQL Server 5.6 on CentOS 7 / RHEL 7

In this tutorial we will learn, how to install MySQL Server 5.6 on CentOS 7 / RHEL 7 . In our previous post, we have installed MySQL Server 5.6 on CentOS 6.x/RHEL 7.x.

In CentOS 7/ RHEL 7 , now MariaDB is introduced as a defualt database. Still many Organisations/Company would like to continue with MySQL. Whereas System Admin who earlier worked on MySQL can easily work on MariaDB. MariaDB is a community-developed fork of the MySQL relational database management system.

MariaDB’s lead developer is Michael “Monty” Widenius, the founder of MySQL and Monty Program AB. He had previously sold his company, MySQL AB, to Sun Microsystems for US$1 billion. MariaDB is named after Monty’s younger daughter, Maria. (Reference taken from Wikipedia)

Install MySQL Server 5.6 on CentOS 7 / RHEL 7

Follow the given below steps to install MySQL Server 5.6 .
You must be login with root user in system

Download the Yum Repo package of MySQL Server 5.6

Download the rpm package, which will create a yum repo file for MySQL Server installation.

yum install wget
wget http://repo.mysql.com/mysql-community-release-el7-5.noarch.rpm

Install mysql-community-release-el7-5.noarch.rpm package

Install this downloaded rpm package by using rpm command.

rpm -ivh mysql-community-release-el7-5.noarch.rpm

After the installation of this package. We will get two new yum repo related to MySQL

[root@localhost ~]# ls -1 /etc/yum.repos.d/mysql-community*
/etc/yum.repos.d/mysql-community.repo
/etc/yum.repos.d/mysql-community-source.repo
[root@localhost ~]#

Installing MySQL Server

By using yum command, now we will install MySQL Server 5.6 . All dependencies will be installed itself.

yum install mysql-server

How to start/stop/restart MySQL Server

Now MySQL Server is installed on your system.

To start MySQL Service
, run command

chkconfig mysqld on
systemctl start mysqld

To stop MySQL Service, run command

systemctl stop mysqld

To restart MySQL Service, run command

systemctl restart mysqld

To get status of MySQL Service, run command

systemctl status mysqld

Reset MySQL root password

On fresh installation of MySQL Server. The MySQL root user password is blank.
For good security practice, we should reset the password MySQL root user.

On newly installed MySQL Server, we generally recommend to use the command script. You have to just follow the instructions.

mysql_secure_installation

In another method,you can log into MySQL server database and reset the password in secure way.

mysql -u root

You will see mysql prompt like this mysql> . Use the below given commands to reset root’s password.

mysql> use mysql;
mysql> update user set password=PASSWORD("GIVE-NEW-ROOT-PASSWORD") where User='root';
mysql> flush privileges;
mysql> quit

phpmyadmin + apach2

sudo apt-get install phpmyadmin

Если у Вас в репозитории свежий пакет phpmyadmin, то в процессе установки он спросит пароль для доступа к базе данных mysql, а так же там он создаст свои таблицы с настройками, а ещё спросит логин и пароль для своего постоянного использования. Затем перезапускаем наш веб-сервер Apache:

sudo /etc/init.d/apache2 restart

Теперь мы смело можем проверить на работоспособность сие дивное веб-приложение. Для этого набираем, если на локальном компьютере то ссылку в браузере:

http://localhost/phpmyadmin

А если с другого компьютера в сети, то пишем тогда:

http://192.168.100.134/phpmyadmin

соответственно вместо 192.168.100.134 у Вас будет своя айпишка сервера, которую и надо соответственно вписать. Если всё прошло удачно, то наслаждаемся пользованием сия дивного продукта, но если не грузится страничка и выдаёт ошибку, то тогда редактируем конфигурационный файлик Apache:

sudo nano /etc/apache2/apache2.conf

И в конец открывшегося файла добавляем строчку:

Include /etc/phpmyadmin/apache.conf

Затем нажимаем клавишу F3 для сохранения, enter — для подтверждения, и F2 — для выхода из файла. Затем нам останется только заново перезагрузить наш вэб-сервер:

sudo /etc/init.d/apache2 restart

Вот теперь то не должно никаких абсолютно проблем возникнуть, для проверки опять же открываем браузер, как было написано чуть выше и проверяем работоспособность, и соответственно радуемся  :) .

pg install with phpmyadmin

link

Для установки нужных нам пакетов пишем в командной строке:

$ sudo apt-get install postgresql postgresql-client postgresql-contrib

Этой командой мы установим сервер и клиент БД и некоторые дополнительные скрипты для работы с БД.

В отличии от привычного мне MySQL, Postres не спрашивает пароль для администратора при установке, поэтому его нужно задать вручную. Суперпользователь БД в PostgreSQL называется postgres. Следующими командами присвоим ему пароль:

$ sudo su postgres -c psql postgres

 postgres=# ALTER USER postgres WITH PASSWORD 'password';
 postgres=# \q

Вместо password пишем свой пароль. Данными командами мы изменили пароль пользователю «postgres» в базе данных «postgres». Теперь нужно задать соответствующий пароль системному пользователю postgres. Для это пишем:

$ sudo passwd postgres

Задаем такой же пароль как и выше.

Далее настроим наш сервер для работы в сети. Для этого своим любимым редактором открываем файл /etc/postgresql/8.3/main/postgresql.conf например:

$ sudo nano /etc/postgresql/8.3/main/postgresql.conf

и в секции «Connections and Authentication» раскомментируем следующие строки:

listen_addresses = 'localhost'

и

password_encryption = on

вместо localhost через запятую пишем IP-адреса на которые хотим повесить PostgreSQL сервер. Например:

listen_addresses = '127.0.0.1, 192.168.1.1'

здесь я повесил сервер на внутренний айпишник, а так же оставил его на локалхосте (если не прописать, то не работает phpPgAdmin консольный клиент).

Если нужно что бы наш сервер был доступен на всех сетевых интерфейсах, вместо IP-адресов ставим ‘*’.

Теперь мы должны определить кто из пользователей сети должен иметь доступ к серверу. Для этого в конец файла /etc/postgresql/8.3/main/pg_hba.conf дописываем строчку:

host    all         all         [ip адрес]          [маска подсети]  md5

вместо [ip адрес] пишем айпи клиента в нашей сети, вместо [маска подсети] нашу маску подсети, например:

host    all         all         192.168.1.2         255.255.255.0  md5

если нужно задать целую подсеть — 192.168.1.0

Перезапускаем сервер:

$ sudo /etc/init.d/postgresql-8.3 restart

На этом сервер должен нормально стартануть и работать как планировалось.

Установим теперь phpPgAdmin:

если Apache уже установлен:

$ sudo apt-get install php5-pgsql phppgadmin wwwconfig-common

если не установлен, устанавливаем и его:

$ sudo apt-get install apache2 php5 php5-pgsql phppgadmin wwwconfig-common

Подключаем файл конфигурации phpPgAdmin в Апач (в Ubuntu он сам не подключается, в Дебиане данное действие не требуется) и перезагружаем веб-сервер:

$ ln -s /etc/phppgadmin/apache.conf /etc/apache2/conf.d/phppgadmin
$ /etc/init.d/apache2 restart

открываем браузер и пишем:

http://ip-адрес_сервера/phppgadmin

мы должны увидеть домашнюю страницу phpPgAdmin.

В целях безопасности вход в phpPgAdmin запрещен от имени пользователя postgres. Поэтому создаем нового пользователя ‘pgadmin’ с правами администратора, для администрирования нашего сервера через веб-интерфейс:

$ sudo -u postgres createuser pgadmin
Shall the new role be a superuser? (y/n)
Shall the new role be allowed to create databases? (y/n)
Shall the new role be allowed to create more new roles? (y/n)

отвечаем на несколько вопросов, что бы наделить нашего пользователя соответствующими привилегиями (я своего сделал суперпользователем), а потом задаем ему пароль следующим образом:

$ sudo su postgres -c psql postgres

 postgres=# ALTER USER pgadmin WITH PASSWORD 'password';
 postgres=# \q

Вместо password пишем пароль и пробуем залогиниться в phpPgAdmin. Сам веб-интерфейс интуитивно понятен и у меня даже на русском языке по умолчанию :) правда не такой функциональный как хотелось бы. Здесь вы можете создать базу данных или пользователя, удалять, импортировать, редактировать и т.п. в зависимости от ваших привилегий и потребностей.

create admin for mysql and workbanch

link

CREATEUSER'username'@'localhost' IDENTIFIED BY'password';GRANTALL PRIVILEGES ON*.*TO'username'@'localhost'WITHGRANTOPTION;CREATEUSER'username'@'%' IDENTIFIED BY'password';GRANTALL PRIVILEGES ON*.*TO'username'@'%'WITHGRANTOPTION;

FLUSH PRIVILEGES;

Also may be:

I added this line to my /etc/ssh/sshd_config file:

KexAlgorithms curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1

and restarted ssh: systemctl restart ssh