Docker remove none images

While you build docker images, it is many untagged images as <none> images. In my tutorial, Docker remove none images or How to stop all CONTAINER ID.

Docker remove none images

To display <none> images:

[huupv@docker nginx-reverse]$ sudo docker images | egrep "^<none>"

The output below:

<none> <none> 55c87cfec131 9 minutes ago 196.6 MB
<none> <none> 8bdd100ab20d 11 minutes ago 196.6 MB
<none> <none> bddbdbcfac80 55 minutes ago 396.5 MB
<none> <none> e8aa668e28d0 19 hours ago 396.5 MB

Docker remove all <none> images

[huupv@docker nginx-reverse]$ sudo docker images | egrep "^<none>" | awk '{print $3}' | xargs sudo docker rmi -f

How to stop all CONTAINER ID

To display all container ID

[huupv@docker ~]$ sudo docker ps | egrep -v "CONTAINER ID" | awk '{print $1}'

The output below:

24e65acc6d21
24da33d6e0d5
09488028a7a9
b3b5926dcb82

To stop all container ID

[huupv@docker ~]$ sudo docker ps | egrep -v "CONTAINER ID" | awk '{print $1}' | xargs sudo docker stop

Thank you for reading the DevopsRoles page!

How to install docker compose

In this tutorial, How to install docker compose on centos. First of all, installed docker on your system. In this preview, Install docker and learn containers on Centos.

What is Docker compose?

Docker compose is tool orchestration manage containers, defining and running multi-container Docker applications, it’s working multiple containers docker application and use the compose file in the YAML format.

How to install docker compose on Centos

Install docker compose on centos 6

The docker compose the latest version, To check the https://github.com/docker/compose/releases

# curl -L https://github.com/docker/compose/releases/download/1.16.1/docker-compose-`uname -s`-`uname -m` -o /usr/local/bin/docker-compose
# chmod +x /usr/local/bin/docker-compose

To check docker compose version:

# docker-compose -v

The screen output terminal:

docker-compose version 1.16.1, build 6d1ac21

Install docker compose on centos 7

To install docker compose

# yum install -y python-pip
# pip install docker-compose

To upgrade all the python packages on Centos 7

# yum upgrade python*

The screen output terminal:

docker-compose version 1.16.1, build 6d1ac21

Testing Docker Compose

To create a new directory and move into it

 $ mkdir hello-world
 $ cd hello-world

To create a new YAML file

$ vim docker-compose.yml

The content file docker-compose.yml as below

 devopsroles-test:
 image: hello-world

To save and exit

To rune the container

$ sudo docker-compose up

The screen output terminal:

 $ docker-compose up
 Pulling devopsroles-test (hello-world:latest)...
 latest: Pulling from hello-world

3619f633e2e6: Pulling fs layer
 3619f633e2e6: Downloading [==================================================>] 3619f633e2e6: Extracting [==================================================>] 93619f633e2e6: Extracting [==================================================>] 93619f633e2e6: Pull complete
 bef02f2f6467: Extracting [==================================================>] bef02f2f6467: Extracting [==================================================>] bef02f2f6467: Pull complete
 Digest: sha256:a69dda95faa021234ab2d92118e9539d0175b46587803e32435ea2e534f2db06
 Status: Downloaded newer image for hello-world:latest
 Creating helloworld_devopsroles-test_1...
 Attaching to helloworld_devopsroles-test_1
 devopsroles-test_1 |
 devopsroles-test_1 | Hello from Docker!
 devopsroles-test_1 | This message shows that your installation appears to be working correctly.
 devopsroles-test_1 |
 devopsroles-test_1 | To generate this message, Docker took the following steps:
 devopsroles-test_1 | 1. The Docker client contacted the Docker daemon.
 devopsroles-test_1 | 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
 devopsroles-test_1 | 3. The Docker daemon created a new container from that image which runs the
 devopsroles-test_1 | executable that produces the output you are currently reading.
 devopsroles-test_1 | 4. The Docker daemon streamed that output to the Docker client, which sent it
 devopsroles-test_1 | to your terminal.
 devopsroles-test_1 |
 devopsroles-test_1 | To try something more ambitious, you can run an Ubuntu container with:
 devopsroles-test_1 | $ docker run -it ubuntu bash
 devopsroles-test_1 |
 devopsroles-test_1 | Share images, automate workflows, and more with a free Docker ID:
 devopsroles-test_1 | https://cloud.docker.com/
 devopsroles-test_1 |
 devopsroles-test_1 | For more examples and ideas, visit:
 devopsroles-test_1 | https://docs.docker.com/engine/userguide/
 devopsroles-test_1 |

Conclusion

Through the article, you can use How to install docker compose as above. I hope will this your helpful. Thank you for reading the DevopsRoles page!

Docker commands line reference

In this tutorial, List all useful commands for docker. How to restart one or more containers and stop one or more containers and so forth. The description useful Docker commands line reference as the link below

What is Docker?

  • Docker is a platform for developers and sysadmins to build, ship and run application”. It’s allow run containers and A container running Application. It’s dependencies on the host operating system.
  • Docker is OS level Virtualization.

All containers are started based on Docker image. To find existing images at https://hub.docker.com/

Docker commands line reference

To use command find an image

$ docker search <name>

To run a container based on a Docker Image. The default, to rune command in the foreground. To rune in the background with option -d. Docker to rune latest version available.

$ docker run <options> <image_name>

Find out running containers

$ docker ps

More details running a container

$ docker inspect <name-container>|<container-id>

Providing logs details running a container

$ docker logs <name-container>|<container-id>

To access a container with <host-port>:<containers-port>

$ docker run -d --name <name-container> -p <host-port>:<containers-port> <Image>

Persisting Data for containers

$ docker run -d --name <name-container> -v <host-dir>:<container-dir> <Image>

accessing to a bash shell inside of a container

$ docker run -it <name-container> bash

List all the images on the host

$ docker images

To use docker build command to build the image

$ docker build -t <name> .

Docker Ignoring Files during Build, to exclude sensitive files during build the image.

$ echo file_name.txt >> .dockerignore

To create Data Container

$ docker create -v /config --name dataContainers busybox

Copy files to data containers

$ docker cp config.conf dataContainers:/config/

Mount Volumes From data containers

$ docker run --volumes-from dataContainers ubuntu ls /config

To Export / Import for data Containers

 $ docker export dataContainer > dataContainer.tar
 $ docker import dataContainer.tar

Docker communicating between containers

$ docker run --link <container-name|id>:<alias> New_container

How to get quick stats on Docker containers

$ docker stats

Conclusion

Through the article, you can use the Docker commands line reference as above. I hope will this your helpful. Thank you for reading the DevopsRoles page!

git command line for beginners

In this tutorial, the Git command line is for beginners, Git server is a repository. I use the command line for my project.

Git is a powerful version control system used for tracking changes in software projects. Here are some basic Git commands for beginners:

Git command line for beginners

Git global setup

 git config --global user.name "PHAN VAN HUU"
 git config --global user.email "pvhuu90@gmail.com"

To create a new repository

 cd BashScripts
 git clone https://gitlab.com/huupv/DevopsSkills.git
 touch README.md
 git add README.md
 git commit -m "add README"
 git push -u origin master

Existing my folder

 cd BashScripts
 git init
 git remote add origin https://gitlab.com/huupv/DevopsSkills.git
 git add .
 git commit -m "Initial commit"
 git push -u origin master -f

Existing git my repository

 cd BashScripts
 git remote rename origin old-origin
 git remote add origin https://gitlab.com/huupv/DevopsSkills.git
 git push -u origin --all
 git push -u origin --tags

I explained the commands below

Git current state

How to list which (unstaged) files have changed, Shows the current status of the repository, including modified and untracked files.

git status

How to list (unstaged) changes to files: (Shows the differences between the working directory and the staging area)

git diff

How to list recent commits: (Displays the commit history of the repository)

git log

Tell me who you are:

git config --global user.name "PHAN VAN HUU"
git config --global user.email "pvhuu90@gmail.com"

To create a new local repository:

git init

To check out a repository

To create a working copy of a local repository

git clone https://gitlab.com/huupv/DevopsSkills.git

For remote server

git clone huupv@host:/path/to/repository

How to add files:

git add File_Name

To commit change but not yet to the remote repository:

git commit -m "Add file to repository commit"

To commit any file with git add:

git commit -a

How to “push” send changes to the master branch of your remote repository:

git push origin master

How to connect to a remote repository:

git remote add origin https://gitlab.com/huupv/BashScripts.git

How to list all currently configured remote repositories:

git remote -v

For Git branches

To create a new branch and switch to it:

git checkout -b <branchname>

To switch from one branch to another:

git checkout <branchname>

To list all the branches in your repository:

git branch

To delete the branch:

git branch -d <branchname>

To push all branches to your remote repository:

git push --all origin

To delete a branch on your remote repository:

git push origin :<branchname>

How to fetch and merge changes on the remote server to your working directory:

git pull

The conclusion

Thought the article, To help you understand the git command line. Thanks for reading my “git command line” post. I’m updating more useful commands line for Git. Thank you for reading the DevopsRoles page!

How to Gitlab SSH key pair

Introduction

In this guide, We’ll explore how to use gitlab SSH keys for Git operations in your projects. Learn the step-by-step process to generate an SSH key pair for GitLab and integrate it with your account.

To effectively use GitLab via SSH, you must create an SSH key pair and link the public key with your GitLab account.

How to do Gitlab SSH key pair

Open a terminal on your Linux system.

If you do not have an SSH key pair, then the error message is as below:

$ cat ~huupv/.ssh/id_rsa.pub
 cat: /home/huupv/.ssh/id_rsa.pub: No such file or directory

To generate a new ssh key pair by running the following command

$ ssh-keygen -t rsa -C "huupv@devopsroles.com" -b 4096

Replace “huupv@devopsroles.com” with your actual email address associated with your GitLab account. You can press Enter to accept the default file path and passphrase (or set a passphrase for added security).

The output Gitlab SSH key pair is below

Generating public/private rsa key pair.
 Enter file in which to save the key (/home/huupv/.ssh/id_rsa):
 Created directory '/home/huupv/.ssh'.
 Enter passphrase (empty for no passphrase):
 Enter same passphrase again:
 Your identification has been saved in /home/huupv/.ssh/id_rsa.
 Your public key has been saved in /home/huupv/.ssh/id_rsa.pub.
 The key fingerprint is:
 2a:16:6d:94:35:a2:02:db:2c:ce:fb:4f:79:56:bf:0b huupv@devopsroles.com
 The key's randomart image is:
 +--[ RSA 4096]----+

To generate 2 files as below:

Private key: id_rsa
Public key: id_rsa.pub

I already have ssh key pair to create on my laptop.

$ cat ~/.ssh/id_rsa.pub

The content public key id_rsa.pub is as below:

ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAgEAwEts938rLe7B1KKgYYBrhCMHFzeumk1IaoVo3rD48qVCig8fCHvp+W3Z2UzHHS9iT1IscXi0Bxq+/fTO9cbB5EznGTIW3I7y26yzIq/6iv3I/biYMmi6EiWCd2Ed2188uZ9aR0+gN4QIAmU8Grh91eaEy04d9H67GF2UT3lqx3PEi7v7aIH6FdkCdOp2YIE25UTuJoMoZ3kjKo02tGP7y/PUw8lbm/ezvYFLBN5l5DfmebDwSBNrR/K84mLWGx3L/bB9XnkEZRSh2vi+YFQ5FMomJA8+RHzfUS5zV3tI8VFDe1bGvcpYxKLKGc1bfKBZSYsOpsKgOofBcENaOJ8l0xCLWMFbJkAKcLEFuwBpLTx75WF7MEaxBnEIWekhhBR5hC+cR2fKEYuZaOYmpBfZUGnIDadad83+3qOQs+50/11AoinHCBOEphWRbn6pk0JP+pyTDsRKEmZ4KNOJt/WNwfVMnCVKb/5wcwCrmQ8ztWilcjT0UdMYUoH4u2IidWV5F38vAdG+LNH5dmKr2pcI7CdgZSXQqppkrvcqMLeH2BprlxuJW8qLc1hYV6HhWYbJc3EX28a6mZfohXLQAgN8HVpBaQ9UAZ33MiDPUhHeIW1OeXSXQHgH5t0CjXqzg3G9/vM7qOUr/27kN+D0ExBPENQf7hZ5Aw24fJl/PLQHAHs= huupv@devopsroles.com

Copy and paste the content id_rsa.pub to the Profile Settings in the Gitlab server web interface. ( step by step as below)

Copy the ssh key to GitLab

Copy the contents of the public key by running the following command: cat ~/.ssh/id_rsa.pub

  1. Copy the entire public key output from the terminal.
  2. Now, log in to your GitLab account using a web browser.
  3. In the top right corner, click on your profile picture and select “Settings.”
  4. From the left-hand side menu, click on “SSH Keys.”
  5. Paste the copied public key into the “Key” field.
  6. Optionally, give a recognizable “Title” to the SSH key (e.g., “My Linux Workstation”).
  7. Click on the “Add key” button to save the SSH key to your GitLab account.
  8. The SSH key is now added to your GitLab account, and you can use SSH to interact with GitLab repositories.

To test the SSH key connection

You can run the following command in the terminal:

Conclusion

Throughout this article, we’ll guide you on how to set up and use an SSH key pair for your project. You’ll learn the straightforward steps to generate an SSH key pair that secures your account. This essential setup enhances the security of your project by ensuring that only authorized users can access it. Follow along to easily create and implement your SSH keys.

You are now ready to use your GitLab SSH key for secure interactions with your repositories. Thank you for reading the DevopsRoles page!

Setting Up a Vagrant Centos box example: A Practical

Introduction

Explore the practical steps to set up a Vagrant CentOS box example in this detailed guide. Whether you’re working with CentOS 6 or 7, this tutorial provides clear instructions and essential tips for using Vagrant to deploy CentOS virtual machines effectively.

In this tutorial, I deployed a centos VM from Vagrantfiles. For example, the Vagrant Centos box example for Centos 6 and Centos 7. To use Vagrant, Virtualbox, and Centos.

The first is to create a Project folder as below:

$ mkdir vagrant_centos
$ cd vagrant_centos
$ vagrant init

To create a vagrant SSH key

[huupv@huupv example01]$ ssh-keygen

The Private key and public key in /home/huupv/project/keys/.ssh

To configure the vagrant SSH key in Vagrantfiles

config.ssh.insert_key = false
config.vm.boot_timeout = 800
config.ssh.private_key_path = ["keys/.ssh/vagrant_rsa", "~/.vagrant.d/insecure_private_key"]
config.vm.provision "file", source: "keys/.ssh/vagrant_rsa.pub", destination: "~/.ssh/authorized_keys"

To configure a vagrant box in Vagrantfiles

For centos 6 or Centos 7

 config.vm.box = “centos/6”
 config.vm.box = “centos/7”

Modifying Vagrant box memory and CPU settings

# Set VM memory size
vb.customize ["modifyvm", :id, "--memory", "512"]
# Set VM cpu size
config.vm.customize ["modifyvm", :id, "--cpus", 2]

Configure Forwarded port network

config.vm.network "forwarded_port", guest: 80, host: 8888
config.vm.network :public_network, :bridge => "eth1", :auto_config => false

To set VM hostname for Guest VM

#Set VM hostname
config.vm.hostname = "Server01"

To install the packages necessary for the Vagrant Centos box

config.vm.provision :shell, path: "VAGRANT_ENV/bootstrap.sh"

Vagrant Centos box example in a Vagrantfile.

VAGRANTFILE_API_VERSION = "2"
 Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
 config.vm.box = "centos/6"
 config.vm.hostname = "Server01"
 config.ssh.insert_key = false
 config.vm.provision :shell, path: "VAGRANT_ENV/bootstrap.sh"
 # Create a private network, which allows host-only access to the machine
 # using a specific IP.
 # config.vm.network :private_network, ip: "192.168.33.10"
 config.vm.network "forwarded_port", guest: 80, host: 8888
 config.vm.network :public_network, :bridge => "eth1", :auto_config => false
 # Share an additional folder to the guest VM
 # config.vm.synced_folder ".", "/vagrant", disabled: true
 # config.vm.synced_folder ".", "/home/vagrant/provision", type: "rsync"
 config.vm.provider :virtualbox do |vb|
 # Set VM memory size
 vb.customize ["modifyvm", :id, "--memory", "512"]
 # these 2 commands massively speed up DNS resolution, which means outbound
 # connections don't take forever (eg the WP admin dashboard and update page)
 vb.customize ["modifyvm", :id, "--natdnshostresolver1", "on"]
 vb.customize ["modifyvm", :id, "--natdnsproxy1", "on"]
 end
 end

To run vagrant up a Virtual Machine, to start guest VM

[huupv@huupv example01]$ vagrant up

Conclusion

This guide demystifies the process of deploying CentOS using Vagrant, making it accessible for developers and IT professionals alike. With these insights, you’re now equipped to streamline your development and testing environments efficiently.

Thought the article, you can use the Vagrant Centos box example as above. I hope will this your helpful. Thank you for reading the DevopsRoles page!

Vagrant triggers backup databases

Introduction

When you running command Vagrant resume, Vagrant halt and vagrant destroy. Then Vagrant triggers backup databases. For example backup Mysql databases for WordPress. Vagrant the essential for DevOps Roles.

Vagrant triggers backup databases

Installing vagrant triggers

$ vagrant plugin install vagrant-triggers

To configure the vagrant triggers database dump

$ vim Vagrantfile

The content as below:

VAGRANTFILE_API_VERSION = "2"
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
#config.vm.box = "digitalquery/wpvagrant"
 config.vm.box = "ubuntu/xenial64"
 config.vm.hostname = "wp"
 config.ssh.insert_key = false
 # Vagrant triggers
 #config.trigger.before :destroy, :stdout => true do
 #config.trigger.before :destroy do
 [:resume, :suspend, :halt, :destroy, :reload].each do |cmd|
 config.trigger.before cmd, stdout: true do
 info "Dumping the database before destroying the VM..."
 run_remote "bash /vagrant/mysql/db_dump.sh"
 #run "vagrant ssh -c 'sh /vagrant/wp-vagrant/mysql/db_dump.sh'"
 end
 end
 end

The databases dump script

$ vim /home/huupv/project/mysql/db_dump.sh

The content db_dump script as below:

#!/bin/bash
 echo "db name is wordpress"
 if [ ! -z "wordpress" ]; then
 now=`date +"%Y_%m_%d-%H-%M-%S"`
 db_dump_file=wordpress"_"$now".sql"
 echo "dumping database before destroy"
 echo "dump file: /vagrant/mysql/db_dumps/$db_dump_file"
 if [ ! -d /vagrant/mysql/db_dumps ]; then
 sudo mkdir /vagrant/mysql/db_dumps
 fi
 mysqldump -u root --password=root wordpress > /vagrant/mysql/db_dumps/$db_dump_file
 if [ ! "$?" -eq 0 ]; then
 echo "DATABASE DUMP FAILED - YOU MAY WISH TO ABORT VAGRANT DESTROY."
 echo "Check /vagrant/VAGRANT_ENV/db_dumps/error.log for more info"
 fi
 fi

Conclusion

How to preserve your MySQL Databases Between Destroy and halt. Vagrant triggers are the plugin. Thank you for reading the DevopsRoles page!

Vagrant SSH key pair Setup: Essential Guide for DevOps Professionals

Introduction

In this tutorial, I will guide you through setting up an Vagrant ssh key pair. We’ll generate the SSH keys, where vagrant_rsa will the private key and vagrant_rsa.pub will serve as the public key. This allows you to log into the Virtual Machine without needing a password. Setting up Vagrant is crucial for those in DevOps roles.

Understanding SSH Key Management in Vagrant

When working with Vagrant, a tool that streamlines the creation and management of virtual development environments, it’s crucial to understand how SSH keys are handled. SSH keys play a vital role in securing access to your Vagrant virtual machines (VMs).

Vagrant SSH Key Location

By default, when you initiate a new Vagrant environment, Vagrant automatically generates an SSH key pair if none exists. This is done to ensure secure, password-less access to the created VM. The location of these SSH keys is typically within the Vagrant project directory .vagrant/machines/<machine-name>/virtualbox/private_key for VirtualBox users. This path might vary slightly depending on the provider you are using, such as VMware or Hyper-V.

Managing Vagrant SSH Keys

It’s important to know that Vagrant configures its VMs to use these automatically generated keys. However, for enhanced security or personal preference, you can configure Vagrant to use a custom SSH key pair. This involves specifying your private key in the Vagrantfile and ensuring the corresponding public key is authorized in the VM. Managing these keys properly ensures that access to your VM is both secure and restricted to authorized users only.

Below is the folder structure for the Vagrant project:

/home/huupv/project
/home/huupv/project/keys/.ssh

Vagrant SSH key pair

The first is to create a vagrant SSH key

Using the ssh-keygen command to create the private key and public key for a vagrant.

ssh-keygen

The output private key and public key files in “/home/huupv/project/keys/.ssh” folder as below:

vagrant_rsa vagrant_rsa.pub

To configure vagrant ssh key in Vagrantfile

To add the lines in the Vagrantfile file as below:

Vagrant.configure("2") do |config|
config.vm.box = "centos/6"
config.ssh.insert_key = false
config.vm.boot_timeout = 800
config.ssh.private_key_path = ["keys/.ssh/vagrant_rsa", "~/.vagrant.d/insecure_private_key"]
config.vm.provision "file", source: "keys/.ssh/vagrant_rsa.pub", destination: "~/.ssh/authorized_keys"
end
  • ~/.vagrant.d/insecure_private_key: You should append this default key. The use config.ssh.insert_key = false to Vagrant not generate a random key.
  • config.ssh.private_key_path: Changing Insecure Key To My Own Key On Vagrant box.

Conclusion

Finishing, We are customizing the vagrant SSH key with a Private/Public key. What you need to Private key saves in the host and the Public key copies authorized_keys into a vagrant box for Virtual Machine. Reference to configure vagrant SSH of the vagrant main site. Thank you for reading the DevopsRoles page!

How to set up a wordpress vagrant: A Comprehensive Guide

Introduction

Setting up WordPress with Vagrant has become a go-to solution for developers seeking a reliable, consistent, and portable environment for web development. Vagrant simplifies the process of creating and configuring virtual environments, ensuring that your WordPress projects are not only portable but also identical across various systems. This guide walks you through the step-by-step process of setting up WordPress Vagrant, from basic installation to advanced configurations.

In this tutorial, I’m set up a WordPress Vagrant, using vagrant box ubuntu with Nginx + MariaDB + WordPress. Vagrant the essential for DevOps Roles.

Benefits of Using Vagrant for WordPress Development

1. Consistent Environments

  • Ensures uniformity between development, staging, and production environments.
  • Avoids the common “works on my machine” problem.

2. Portable and Reproducible

  • Easily share development environments across teams.
  • Rapidly recreate environments in case of errors or new projects.

3. Integration with Popular Tools

  • Works seamlessly with VirtualBox, Docker, and other virtualization tools.
  • Supports provisioning tools like Ansible, Chef, and Puppet.

Prerequisites

Before diving into the setup, ensure you have the following:

Required Tools

System Requirements

  • At least 8GB of RAM.
  • 20GB of free disk space.
  • A stable internet connection.

Step-by-Step Guide to Setting Up WordPress with Vagrant

The structures files and folders wordpress vagrant as below:

[huupv@localhost project]$ pwd
/home/huupv/project
[huupv@localhost project]$ ls -F
keys/ nginx/ Vagrantfile var/
mysql/ php/ VAGRANT_ENV/ wp/

To configure Vagrantfile

vim Vagrantfile

The content as below:

VAGRANTFILE_API_VERSION = "2"
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
config.vm.box = "ubuntu/xenial64"
config.vm.hostname = "wp"
config.ssh.insert_key = false
#config.vm.boot_timeout = 800
#config.ssh.username = vagrant
#config.ssh.password = vagrant
#config.ssh.private_key_path = ["keys/.ssh/vagrant_rsa", "~/.vagrant.d/insecure_private_key"]
#config.vm.provision "file", source: "keys/.ssh/vagrant_rsa.pub", destination: "~/.ssh/authorized_keys"
config.vm.provision :shell, path: "VAGRANT_ENV/bootstrap.sh"
config.vm.network "forwarded_port", guest: 80, host: 8888
config.vm.network :public_network, :bridge => "eth1", :auto_config => false
config.vm.provider :virtualbox do |vb|
# Set VM memory size
vb.customize ["modifyvm", :id, "--memory", "512"]
# these 2 commands massively speed up DNS resolution, which means outbound
# connections don't take forever (eg the WP admin dashboard and update page)
vb.customize ["modifyvm", :id, "--natdnshostresolver1", "on"]
vb.customize ["modifyvm", :id, "--natdnsproxy1", "on"]
end
end

To configure file vagrant bootstrap.sh

vim VAGRANT_ENV/bootstrap.sh

The content as below:

#!/bin/bash
echo "Vagrant box (Ubuntu 16.04 + nginx + php7.0 + MariaDB + WordPress."
 echo "Updating apt-get"
 sudo apt-get -y update
# Nginx
 echo "Installing Nginx"
 sudo apt-get install -y nginx
# MySQL
 echo "Preparing for MySQL Installation"
 sudo apt-get install -y debconf-utils
 sudo debconf-set-selections << "mysql-server mysql-server/root_password password root"
 sudo debconf-set-selections << "mysql-server mysql-server/root_password_again password root" echo "Installing MySQL" #sudo apt-get install -y mysql-server-5.7
 sudo apt-get install -y mariadb-server mariadb-client php7.0-mysql
 sudo rm -f /etc/mysql/my.cnf
 sudo rm -f /etc/alternatives/my.cnf
 sudo cp /vagrant/mysql/my.cnf /etc/alternatives/my.cnf
 sudo ln -s /etc/alternatives/my.cnf /etc/mysql/my.cnf
 ls -ll /etc/mysql/my.cnf
 echo "Installing PHP and MySQL module"
 sudo apt-get install -y php-fpm php-mysql
# Nginx Config
 echo "Overwriting default Nginx config to work with PHP"
 sudo rm -rf /etc/nginx/sites-available/default
 cp /vagrant/nginx/default.conf /etc/nginx/sites-available/default
# php cli
 sudo sed -i "s/error_reporting = .*/error_reporting = E_ALL/" /etc/php/7.0/fpm/php.ini
 sudo sed -i "s/display_errors = .*/display_errors = On/" /etc/php/7.0/cli/php.ini
 sudo sed -i "s/memory_limit = .*/memory_limit = 30M/" /etc/php/7.0/cli/php.ini
 sudo sed -i "s/;date.timezone.*/date.timezone = UTC/" /etc/php/7.0/cli/php.ini
# php fpm
 sudo sed -i "s/error_reporting = .*/error_reporting = E_ALL/" /etc/php/7.0/fpm/php.ini
 sudo sed -i "s/display_errors = .*/display_errors = On/" /etc/php/7.0/fpm/php.ini
 sudo sed -i "s/;cgi.fix_pathinfo=1/cgi.fix_pathinfo=0/" /etc/php/7.0/fpm/php.ini
 sudo sed -i "s/memory_limit = .*/memory_limit = 30M/" /etc/php/7.0/fpm/php.ini
 sudo sed -i "s/upload_max_filesize = .*/upload_max_filesize = 100M/" /etc/php/7.0/fpm/php.ini
 sudo sed -i "s/post_max_size = .*/post_max_size = 100M/" /etc/php/7.0/fpm/php.ini
 sudo sed -i "s/;date.timezone.*/date.timezone = UTC/" /etc/php/7.0/fpm/php.ini
# Restarting Nginx for config to take effect
 echo "Restarting Nginx for changes to take effect"
 sudo service nginx restart

echo "Setting Ubuntu (user) password to \"vagrant\""
echo "ubuntu:vagrant" | chpasswd
# Services restart
 sudo systemctl restart mysql.service
 sudo systemctl restart nginx.service
 sudo systemctl restart php7.0-fpm.service
sudo mysql -u root -p -e 'show databases'
 #Create wordpress databases
 bash /vagrant/mysql/create_database.sh
 #To install and configure wordpress
 cd /tmp
 curl -O https://wordpress.org/latest.tar.gz
 tar xzvf latest.tar.gz
 sudo cp /tmp/wordpress/wp-config-sample.php /tmp/wordpress/wp-config.php
 mkdir /tmp/wordpress/wp-content/upgrade
 sudo cp -a /tmp/wordpress/* /var/www/html
 sudo find /var/www/html -type d -exec chmod g+s {} \;
 sudo chmod g+w /var/www/html/wp-content
 sudo chmod -R g+w /var/www/html/wp-content/themes
 sudo chmod -R g+w /var/www/html/wp-content/plugins
 sudo rm -f /var/www/html/wp-config.php
 sudo cp /vagrant/wp/wp-config.php /var/www/html/wp-config.php
 sudo usermod -a -G www-data ubuntu
 sudo chown -R ubuntu:www-data /var/www/html
 sudo systemctl restart nginx.service
 echo "Cleaning up additional setup files and logs"
 #sudo rm -r /var/www/html
 #sudo rm /var/www/ubuntu-xenial-16.04-cloudimg-console.log

To configure MySQL my.cf file

vim mysql/my.cnf

The content as below:


[client]
port = 3306
socket = /var/run/mysqld/mysqld.sock
[mysqld_safe]
socket = /var/run/mysqld/mysqld.sock
nice = 0

[mysqld]
user = mysql
pid-file = /var/run/mysqld/mysqld.pid
socket = /var/run/mysqld/mysqld.sock
port = 3306
basedir = /usr
datadir = /var/lib/mysql
tmpdir = /tmp
lc-messages-dir = /usr/share/mysql
skip-external-locking
bind-address = 0.0.0.0
key_buffer_size = 16M
max_allowed_packet = 16M
thread_stack = 192K
thread_cache_size = 8
myisam-recover = BACKUP
query_cache_limit = 1M
query_cache_size = 16M
log_error = /var/log/mysql/error.log
expire_logs_days = 10
max_binlog_size = 100M
[mysqldump]
quick
quote-names
max_allowed_packet = 16M

[mysql]
[isamchk]
key_buffer_size = 16M
!includedir /etc/mysql/conf.d/

To create a database for WordPress

vim mysql/create_database.sh

The content as below:

#!/usr/bin/env bash
if [ ! -z "wordpress" ] ; then
echo "creating database"
 sudo mysql -u root -p'root' -e "CREATE DATABASE IF NOT EXISTS wordpress;"
if [ ! -z "wp_db_user" ]; then
 echo " adding custom user"
 sudo mysql -u root -p'root' -e "GRANT ALL ON wordpress.* TO 'wp_db_user'@'localhost' IDENTIFIED BY '123456789'"
 sudo mysql -u root -p'root' -e "FLUSH PRIVILEGES;"
 sudo mysql -u root -p'root' -e 'show databases;'
 fi
else
 echo "No database name specified - skipping db creation"
fi

To configure file wp-config.php for WordPress vagrant

vim wp/wp-config.php

The content as below:

<?php
define('DB_NAME', 'wordpress');
/** MySQL database username */
 define('DB_USER', 'wp_db_user');
/** MySQL database password */
 define('DB_PASSWORD', '123456789');
/** MySQL hostname */
 define('DB_HOST', 'localhost');
/** Database Charset to use in creating database tables. */
 define('DB_CHARSET', 'utf8');
/** The Database Collate type. Don't change this if in doubt. */
 define('DB_COLLATE', '');
 define('AUTH_KEY', 'put your unique phrase here');
 define('SECURE_AUTH_KEY', 'put your unique phrase here');
 define('LOGGED_IN_KEY', 'put your unique phrase here');
 define('NONCE_KEY', 'put your unique phrase here');
 define('AUTH_SALT', 'put your unique phrase here');
 define('SECURE_AUTH_SALT', 'put your unique phrase here');
 define('LOGGED_IN_SALT', 'put your unique phrase here');
 define('NONCE_SALT', 'put your unique phrase here');
 $table_prefix = 'wp_';
 define('WP_DEBUG', false);
 /** Absolute path to the WordPress directory. */
 if ( !defined('ABSPATH') )
 define('ABSPATH', dirname(__FILE__) . '/');
/** Sets up WordPress vars and included files. */
 require_once(ABSPATH . 'wp-settings.php');
 define('FS_METHOD', 'direct');

To configure file nginx.conf

vim nginx/default.conf

The content as below:

server {
 listen 80 default_server;
 listen [::]:80 default_server ipv6only=on;
 root /var/www/html/;
 index index.php index.html index.htm;
 client_max_body_size 20M;
 server_name devopsroles.com;
 location / {
 try_files $uri $uri/ /index.php?$args;
 }
 error_page 404 /404.html;
 error_page 500 502 503 504 /50x.html;
 location = /50x.html {
 root /usr/share/nginx/html;
 }
 location ~ \.php$ {
 try_files $uri =404;
 fastcgi_split_path_info ^(.+\.php)(/.+)$;
 fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
 fastcgi_index index.php;
 include fastcgi_params;
 fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
 }
 }

Vagrant up running for WordPress

[huupv@localhost ~]$ cd /home/huupv/project/
[huupv@localhost project]$ vagrant up

FAQs

Q1: Why use Vagrant over Docker for WordPress?

While Docker is lightweight, Vagrant provides a full virtualized environment, making it suitable for developers needing an environment closer to production.

Q2: Can I use a different Linux distribution?

Yes, replace ubuntu/bionic64 in the Vagrantfile with the desired box name from Vagrant Cloud.

Q3: How do I update the Vagrant environment?

Use the following commands:

  • To apply updates: vagrant provision
  • To rebuild the environment: vagrant destroy -f && vagrant up

Q4: How do I troubleshoot Vagrant errors?

  • Check the Vagrant logs in the project directory.
  • Refer to the Vagrant Documentation.

External Resources

Conclusion

You have to set up a Vagrant WordPress Nginx + MariaDB. Setting up WordPress with Vagrant is a powerful way to ensure consistency and efficiency in web development. By following this guide, you can create a robust development environment tailored to your needs. Whether you’re a solo developer or part of a team, Vagrant offers the flexibility and reliability to elevate your WordPress projects. I hope will this your helpful. Thank you for reading the DevopsRoles page!

Your Complete Guide to Useful vagrant commands line

Introduction

Master the essentials of Useful vagrant commands line. Whether you’re starting, stopping, or managing virtual machines, this article provides the necessary commands to efficiently control your Vagrant environments. Ideal for developers and IT professionals looking to streamline their workflow in virtual machine management.

In this tutorial, I guide using the useful Vagrant commands line for Virtual Machines such as: Starting and Stopping a VM so forth. Vagrant the essential for DevOps Roles.

Useful vagrant commands line

Vagrant commands for Virtual Machine

Initialize Vagrant with a Vagrantfile

# vagrant init

Initialize the vagrant with a specific box. To find a box, https://app.vagrantup.com/boxes/search
Vagrant commands for starting a Virtual Machine
To run the first vagrant up a Virtual Machine, to start vagrant environment

# vagrant up

To resume a Virtual Machine

# vagrant resume

Restarting a Virtual Machine

# vagrant reload

Vagrant commands for stopping a Virtual Machine
To stop a Virtual Machine

# vagrant halt

To suspend a Virtual Machine

# vagrant suspend

Vagrant commands cleaning up a Virtual Machine
To stop and delete all traces of the Virtual Machine

# vagrant destroy

Vagrant commands for Boxes
To list all installed boxes on your computer

# vagrant box list

To download a box image to your computer

# vagrant box add

Checking for updates vagrant box update

# vagrant box outdated

To delete a box from the machine

# vagrant boxes remove

The packages a running Virtualbox environment in a reusable box

# vagrant package

To snapshot a Virtual Machine
The VM-name often defaults. To roll back at a later time.

# vagrant snapshot save [options] [vm-name]

The useful vagrant commands
To get the vagrant version

# vagrant -v

The output status of the vagrant machine

# vagrant status

The output status of all vagrant machines

# vagrant global-status

The same as above, but prunes invalid entries

# vagrant global-status --prune

To use the debug flag to increase the verbosity of the output

# vagrant provision --debug

Vagrant can be configured to deploy code!

# vagrant push

To Runs vagrant up, forces provisioning and logs all output to a file

# vagrant up --provision | tee provision_2017.log

Conclusion

This compilation of useful Vagrant commands will empower you to manage your virtual machines more effectively. By familiarizing yourself with these commands, you can optimize your development environment and enhance your productivity. For a detailed exploration of each command, refer to the full guide. I hope will this your helpful. Thank you for reading the DevopsRoles page!

Devops Tutorial

Exit mobile version