Vagrant for kids, or how to easily get a customized server for developing web applications on Windows

Hello, my dear lover of working with Composer, creating your next cool project on one of the trendy frameworks. Or maybe you are a front-end master writing complex things in JS and CSS, compiling them from jsx and less files, installing libraries through Bower, and collecting a project in some Grunt, passing the code with unit tests and , of course, then uploading all this to github ... If all this is part of your daily life, then praise the Almighty, congratulations: you went through all these tests and did not even break your brain. From now on, you are one of those happy people who spent more than one week understanding how to correctly configure this whole bunch of tools, and also, you are one of those who can dominate, dominate and humiliateshine your knowledge in Habr's comments on articles of other, less agile and smart colleagues in the shop ...

But ... maybe you are just one of those who only dreams of such perversions of the manipulations of the masters of developing modern web applications?) Then I hasten to please you : I recently learned a couple of useful things and realized that this is a real gift for beginner developers. And I decided to write this article.

For several years now I’ve heard about Vagrant, and you, too, probably have already heard about this tool for quick deployment of configured virtual machines. But, every time I read another article about Vagrant, I was pushed away by the excessive complexity of the instructions for it. I don’t like to boggle my head with unnecessary information: it was somehow easier all the time to put everything you need through "sudo apt-get install [program-name]" and manually add new configs to nginx, taking as a basis the old ones. But, having read the instructions in the documentation for Laravel the other day , I realized that everything wasn’t so scary, and the desire to teach my friend how to program was the last factor, because of which I still got to set up Vagrant on my machine ...

Laravel developers have created their own virtual machine image for Vagrant, which already contains all the tools and tools you need for a happy development. As a result, together with the small Homestead utility, also carefully provided by Laravel to work with their image, working with it is really quite simple. A list of the main components installed in their image can be found in the documentation . Among other tools not listed in it are things like, for example, composer and git. In general, there is already everything you need. You and I can only figure out a little how Vagrant and Homestead work and calmly use this whole thing in our daily work.

And it is not necessary to use this set only for projects based on Laravel: the Homestead script provides simple tools for conducting the development of several projects at once, through a simple configuration file allowing you to manage databases and nginx server configurations. As a result, we get almost an analogue to Denwer, but at the same time we are dealing with a full-fledged linux server, which, if necessary, we can easily start managing manually and install other components on it, and thus grow into more serious and experienced developers.

Preset


In fact, all you have to do is install VirtualBox and Vagrant on your computer and dig deeper into their settings. In the article, I will only talk about Windows users, since Linux users, I think, can do everything themselves according to the instructions in the documentation. Of course, everything is not without problems. If your Windows username is written in Russian letters (like mine), then get ready for errors while executing the commands. In this case, I recommend creating a system environment variable VAGRANT_HOME with an indication of the folder without Russian characters (don’t know how to do this? Read about it here , for example), and also open VirtualBox’s settingsand specify the virtual machine storage folder, which also does not have Russian characters. That's it, now these tools should work correctly and not produce errors.

So, we created the basis for ourselves, it's time to write some commands :) Press the keys Win + R on the keyboard , drive the phrase “cmd” into the window that opens, press Enter and get to the command line. By the way, you may have to restart the machine after installing Vagrant so that its command becomes available in the console. So, for starters, let's just type the word “vagrant” in the console and check whether our tool is installed correctly:



Everything is fine with me. If you encounter problems, then check your PATH variable, it should have a path to the Vagrant binary. And reboot the machine if you have not done so.

Further in the official documentation we are offered to clone using git or, even worse, to install the Homestead library on your computer through composer. I have neither git on Windows, nor composer. And anyway: I was going to install this virtual machine just in order to save myself from manual trouble with installing all these tools ... Therefore, let's still not deal with perversions and just, in the old fashioned way, download the zip archive from github -pages of this library on your computer and unpack it into some daddy :)

Unpacked? Now, to install the library on the computer, you need to run the homestead init command. But here again the trouble: this command will work with us only when Composer and the main Laravel libraries are installed on our computer. Another option is to run the init.sh script , which is right next to it, but to run it, we still need a Linux interpreter. In general, again to put a bunch of stuff ... As you can see, under Windows there is no simple solution. So let's do a couple of things again manually: open the contents of the init.sh fileand study it. There are only 11 lines of code. As you can see, in order to “install” the library, we just need to copy several files to the ~ / .homestead folder (the ~ sign denotes the current user's home directory, I have it “C: \ Users \ Ahmadullin \”). If we analyze how their scripts work, we will conclude that we need the following files from there:

  • src / stubs / Homestead.yaml - to ~ / .homestead folder
  • src / stubs / after.sh - to the ~ / .homestead folder
  • src / stubs / aliases - to the ~ / .homestead folder
  • Vagrantfile
  • scripts / * (all files in this folder)

Create a .homestead folder in the user's home directory and copy these files into it: this will be the folder with your control scripts through which we will manage our virtual machine. By the way, you will not be able to create a file that begins with a dot through the standard Windows interface. Use something like Far or Total Commander to solve this problem. So, in the end, I got the following picture: Voot ... It's a completely different matter. We are almost ready to work with our virtual machine. To access our machine, we also need to create SSH keys for ourselves. Here, the Putty toolkit will help us, which we will also subsequently use to manage our server. Download software PuttyGen



and use it to generate our private and public keys, and save them to the ~ / .ssh folder. To generate, click the “Generate" button, then move the mouse a little in the center of the program to generate a random key, and then you can save your key. Also, when saving, the program will offer to fill in the “key passphrase” - but at this stage we don’t need it, so save your key without a password and do not pay attention to the fact that Putty will warn against creating such a key. After all, we only have a test machine, and not a real combat server, so all this is not so scary.

Save the public key under the following name: "~ / .ssh / id_rsa.pub". At the same time, we need to save the private key in two formats: standard for Putty (Save private key button, file name ~ / .ssh / putty_private.ppk, for example), and in OpenSSH format (“Export OpenSSH key” item in the Conversions menu , the file name should be "~ / .ssh / id_rsa"). We need the first private key to connect to the server through the Putty program, and the second to configure and initialize the server through Homestead scripts. As a result, we should get something like this with key files: Now we just have to specify some settings for our server before starting, if necessary. Open the Homestead.yaml file in any editor



. This is the only settings file through which we can specify all the main parameters of our virtual machine. The standard settings are already well written, and for starters we don’t have to change anything here, I’ll just briefly explain its contents: the “ folders ” section indicates the connection between the directories of the virtual machine and your real system so that you can easily edit files in the virtual machine through your favorite editor in the main system. The " sites " section is the nginx settings, and again, everything is very simple: we just set the domain and directory relationship on the server. The " databases " section lists the names of the databases that will be created when the virtual machine is initialized. That, in fact, is all you need to know about configuring our system.

PS Yes, and since the folder “~ / Code” by default indicates the association of the ~ / Code folder with a similar folder in the virtual machine, do not forget to create this directory in your user’s folder. Subsequently, through it we will be able to work with the files of your server.

PPS And yet, keep in mind that the yaml format is slightly different in its approach to data storage. Therefore, if you add your own parameters there, consider that the number of spaces here matters, because a hierarchy of data is defined through them. Therefore, set such indents to new objects that are already in the file. You can read more about this format, for example, on Wikipedia .

Well, finally, we come to the most interesting ...

Virtual Server Launch


Let's try to run our virtual machine! Open the command line to the ~ / .homestead folder and execute the magic command in it:
vagrant up


If you did everything right, then you will start downloading the VirtualBox image from the Laravel developers, and the picture will be something like this: If Vagant informed you about any problem, do not despair: carefully study the error text and try to drive its text into Google. Most likely, there are already many people who have encountered a similar problem and have somehow solved it. If the image successfully downloaded to your computer, and an error occurred while the machine was loading, then try opening VirtualBox and launching it manually, without Vagrant, and see what happens. Vagrant is, in fact, just an add-on to VirtualBox, and you can easily run the virtual machine it has built on its own, if necessary.




If everything went fine ... Then, after a few minutes of Vagrant's work, your virtual machine will be fully configured and install all the necessary components and parameters. And you can already safely connect to your full server. For this, you can use, for example, Putty.

Server connection


Let 's download the putty.exe file and connect using it to our server. Configure the program as follows: specify the server address, port and user , and also, in the " Connection -> SSH -> Auth " section, do not forget to specify the address for the private key generated by you, and then save all these settings in the session under some name , so as not to drive them every time you start the program, and feel free to click the "Open" button. If you were careful and did everything right, the terminal window of your own virtual server will open in front of you: PS



the following problem was detected on some machines: Vagrant for some reason does not accept the key file created in Putty and generates its own, in his opinion, more secure. This key is saved at the address "~ \ .homestead \ .vagrant \ machines \ default \ virtualbox \ private_key". If you cannot connect using your key to the server, then you need to use the key generated by Vagrant. Before using it, open the PuttyGen program again, import the file created by Vagrant into it (the Conversions -> Import key item) and save it in putty format (the “save private key” button), and then use this file to connect to the server via putty.

Well done, fighter! The first milestone on the road to conquering the world of professional web application development has been passed. Now, let's write a couple more commands and install Laravel, just to make sure that everything works correctly on our server. Enter the following two commands in turn on your server:
cd Code
composer create-project laravel/laravel Laravel --prefer-dist

And go get some tea. When you get back, open the very ~ / Code folder that you created in your home directory, and if everything went well, then you should expect a surprise there :) That's it: the server sniffed something at home, and we got the output on your real computer, the Laravel folder with all the necessary framework files. It remains to do a little in order to see our application in the browser: open the hosts file in administrator mode to be able to edit it, and add the following line there:




192.168.10.10 homestead.app

Now open your homestead.app address in your browser . Well, what is visible? I have this picture: If you squint enough, you can see the Laravel logo :) Well, you can still select the letters with the mouse, so it will be more visible. As an exercise, let's fix it a bit. You can open the file " ~ \ Code \ Laravel \ resources \ views \ welcome.blade.php " and delete the lines "color: # B0BEC5;" and "font-family: 'Lato';" in the first twenty lines of the source code. And then save this file and refresh your page. It seems that it got better ?)





In general, this is almost everything. If you got to this part of the article and everything worked out for you, it means that you are a great fellow, and you now have a full-fledged own web server, in which all the technologies necessary for the work are already collected for you. It remains only to talk a little about how to stop it, update its configuration and completely remove it from the system. To do this, use the following Vagrant commands, and do not forget that you should be in the ~ / .homestead directory:

# Включить машину
vagrant up           
# Выключить машину
vagrant halt           
# Снова настроить машину с помощью скриптов Homestead.
# Если ты изменишь файл конфигурации - выполни эту команду,
# и Vagrant снова настроит твою машину
vagrant provision  
# Полностью удалить виртуальную машину из системы.
# Будь осторожен, это удалит также базу данных, поэтому не
# забудь сделать её резервную копию перед выполнением данной команды 
vagrant destroy
# Есть у Vagrant'а еще вот такая замечательная команда для быстрого
# подключения к серверу, но так как мы сидим в Windows, просто так её
# использовать не получится, придётся, как обычно, поднапрячься и
# и установить линуксовую программу "ssh" на свой компьютер.
# Да и если всё сделать, то у тебя всё равно будут проблемы с передачей
# туда кода из буфера обмена, поэтому я всё-таки даю совет: используй Putty и
# радуйся жизни, лучше неё я ничего еще не видел под винду
vagrant ssh


Everything written in this article is a very brief description of all the features of Vagrant, study the official documentation and other articles on this tool if you have a desire to understand it more deeply. And I also advise you to read the comments on this article, sometimes there are also different smart people who write useful things. Well, that’s all. It seems the article is finished. Hope it will benefit people. And all the best to you, dear developers :)

Also popular now: