Устанавливаем CentOS в VirtualBox

CentOS является одной из популярных систем на базе Linux, и по этой причине многие пользователи хотят с ней познакомиться. Устанавливать ее в качестве второй операционной системы на свой ПК — вариант не для каждого, но вместо этого можно поработать с ней в виртуальной, изолированной среде под названием VirtualBox.
Шаг 1: Скачивание CentOS
Скачать CentOS можно с официального сайта совершенно бесплатно. Для удобства пользователей разработчики сделали 2 вариации дистрибутива и несколько способов закачки.
Сама операционная система есть в двух версиях: полная (Everything) и урезанная (Minimal). Для полноценного знакомства рекомендуется скачать полную версию — в урезанной нет даже графической оболочки, и для обычного домашнего использования она не предназначена. Если же вам нужна урезанная, на главной странице CentOS нажмите «Minimal ISO». Оно скачивается ровно такими же действиями, что и Everything, загрузку которой мы рассмотрим ниже.
Скачать версию Everything можно через torrent. Поскольку примерный размер образа составляет порядка 8 ГБ.
Для скачивания выполните следующее:
- Нажмите по ссылке «ISOs are also available via Torrent.»

- Выберите любую ссылку из отобразившегося списка зеркал с torrent-файлами.

- Найдите в открывшейся публичной папке файл «CentOS-7-x86_64-Everything-1611.torrent» (это примерное название, и оно может быть немного другим, в зависимости от текущей версии дистрибутива).

Шаг 2: Создание виртуальной машины для CentOS
В VirtualBox каждая устанавливаемая операционная система нуждается в отдельной виртуальной машине (VM). На этом этапе выбирается тип системы, которая будет установлена, создается виртуальный накопитель и настраиваются дополнительные параметры.
- Запустите VirtualBox Менеджер и нажмите на кнопку «Создать».

- Впишите имя CentOS, и остальные два параметра заполнятся автоматически.

- Укажите объем оперативной памяти, который вы можете выделить для запуска и работы операционной системы. Минимум для комфортной работы — 1 ГБ.


На этом установка VM заканчивается.
Шаг 3: Настройка виртуальной машины
Этот этап необязателен, но будет полезен для некоторых базовых настроек и общего ознакомления с тем, что можно изменить в VM. Для входа в настройки нужно нажать правой кнопкой мыши по виртуальной машине и выбрать пункт «Настроить».

Во вкладке «Система» — «Процессор» можно увеличить количество процессоров до 2. Это даст некоторый прирост к производительности CentOS.


Перейдя в «Дисплей», можете добавить некоторое количество МБ к видеопамяти и включить 3D-ускорение.

Остальные настройки можно выставить по своему усмотрению и возвращаться к ним в любой момент, когда машина не запущена.
Шаг 4: Установка CentOS
Основной и последний этап: инсталляция дистрибутива, который уже был скачан.

- Выделите кликом мыши виртуальную машину и нажмите на кнопку «Запустить».
- После запуска VM нажмите на папку и через стандартный системный проводник укажите место, куда вы скачали образ ОС.
Выберите ваш язык и его разновидность.

Если вы хотите сделать в CentOS жесткий диск с одним разделом, то просто зайдите в меню с настройками, выделите виртуальный накопитель, который был создан вместе с виртуальной машиной, и нажмите «Готово»;

По умолчанию стоит минимальная установка, но она не имеет графического интерфейса. Вы можете выбрать, с какой средой будет установлена ОС: GNOME или KDE. Выбор зависит от ваших предпочтений, а мы рассмотрим инсталляцию с окружением KDE.
После выбора оболочки в правой части окна появятся дополнения. Галочками можете отметить то, что хотели бы видеть в CentOS. По завершении выбора нажмите «Готово».
При желании назначьте этого пользователя администратором, установив соответствующую галочку.
Придумайте пароль для учетной записи и нажмите «Готово».
Кликните на регулятор, и он сдвинется вправо.
Теперь вы можете начинать пользоваться операционной системой CentOS.

Установка CentOS — одна из самых простых, и может быть без труда выполнена даже новичком. Эта операционная система по первым впечатлениям ощутимо может отличаться от Windows и быть непривычной, даже если вы ранее пользовались Ubuntu или MacOS. Однако в освоении этой ОС не возникнет особых сложностей благодаря удобному окружению рабочего стола и расширенному набору приложений и утилит.
Install CentOS on VirtualBox on Windows Host and Connect from PuTTY
The most essential resource that every computer science professionals and students need is a personal Linux machine where they can install, learn, test and explore new things to expand their knowledge and skills. For many of us, the resources available at offices and schools might be strictly for business purpose, shared with other users, and have restrictions to install and experiment with third party stuffs on them. So the best option is, run a Linux server inside a Virtual Machine (VM) running on our Windows or Linux desktop, where we can do almost anything, or even screw up the system without caring anybody. Also it enables us to work virtually uninterrupted from network failures on remote machines, because the local VM comes along with us wherever we take our PC.
Here I am describing how to install CentOS 7 on Oracle VirtualBox (VM) running on Windows 10 host and connect to it via SSH session from PuTTY.
Step 1: Install Oracle VirtualBox
Download and install Oracle VirtualBox for windows hosts from here: https://www.virtualbox.org/wiki/Downloads
Step 2: Download CentOS ISO
Download the CentOS ISO image from one of the official mirrors listed here.
Choose CentOS-7-x86_64-Minimal-1908.iso file from the index page of the mirror you selected.
Note: Alternatively, we can download CentOS-7-x86_64-NetInstall-1908.iso which is pretty small in size and will automatically download the required files from the mirror during installation.
What is Minimal ISO?
The minimal iso provides an absolutely bare OS image. The installation won’t have any desktop environment or GUI interface. It is a good option if you prefer to have a server environment with only core OS packages and terminal access. After it is installed, you can install other packages via “yum install” as per your requirements. Also, if you want, you can change it to a standard server (like the one provided by “Everything iso”) by running “yum groupinstall base”.
Step 3: Create Virtual Machine (VM)
Refer to the steps given below.
a. Open the Oracle VirtualBox application. Click on ‘New’ and enter the details as required and click Next.
b. Select the RAM you prefer to allocate to the VM. I selected 3072 MB (3GB). Click Next.
c. Select ‘Create a virtual hard disk now’. Click Next.
d. In ‘Hard disk file type’ screen, I selected VMDK because, I would like to experiment with VMWare later using the image created here. You can leave it as VDI also.
VDI: Oracle VM VirtualBox’s own container format.
VHD: The format used by Microsoft.
VMDK: A popular and open VMDK container format that is used by many virtualization products, such as VMware.
e. On the next screen for ‘Storage on physical hard disk’, leave the selection as ‘Dynamically allocated’.
f. On the next screen for ‘File allocation and size, I selected 10 GB. Click Create.
Step 4: Start Virtual Machine
a. The VM we created in Step 3 can be found in the VirtualBox now. Select it and click ‘Settings’.
b. On the settings windows, go to Storage → Controller IDE → Empty → Optical Drive → Choose a disk file → Choose the iso file that we downloaded in Step 2. Then click OK.
c. Click ‘Start’ Button when you are on previous screen.
d. A dialog for ‘select startup disk’ will appear showing the iso we selected in previous step. Click ‘Start’
Note: This dialog appears only first time.
e. VM will start booting from the selected disk.
Sep 5: Install CentOS
a. When the VM starts, choose ‘Install CentOs 7’ from the first boot menu by navigating with the up & down keys and press Enter key to select.
b. On the next screen, set language preferences when prompted.
c. On the next screen, choose Date & Time and other settings as given below:
Installation Source → Local Media
Software Selection → Minimal Install
Installation Destination → Automatic Partitioning
d. On the same screen click on ‘Network and Hostname’. Ethernet is disabled by default. Use the slider to enable (refer to the image below), so that this VM can use the host’s network to connect to internet. Click ‘Done’.
Note: If you do not enable the network now, you can still do it after installation via Linux system settings. Step 7 will detail this.
e. When everything is configured, the ‘Begin Installation’ button will become enabled. Click on it to start the installation.
f. While it installs, click on the ‘ROOT PASSWORD’ to set the password for root.
Note: If it complains that the password is too short or weak, click on the ‘Done’ button again and it will accept the password you entered.
g. Click on the ‘CREATE USER’ to add new users. I created a user as shown below:
Full Name: User 01
User name: user01
Make this user administrator: yes
Require password to use this account: yes
Password: ******
Note: We can skip setting ROOT PASSWORD and CREATE USER now and do it after installation via Linux commands . Step 6 will detail how to do this.
h. When all mandatory settings are configured, the ‘Finish Configuration’ button will be enabled. Click on it.
i. When installation is completed successfully, ‘Reboot’ button will be enabled. Click it to reboot the VM.
j. VM will reboot and prompt you to login. Login as the root or the user you created. In my case I login as user01.
Step 6: Create Users, Change Passwords
Note: If you have set the root password, created an administrator user and set password for it during installation, you may skip this step, unless you want to create some other users.
Tip: It is highly recommended to set password for root and the other users we create. We wont be able to SSH to a user account that doesn’t have password set unless we modify the ssh configuration to override this behavior.
a. Login as root, and use passwd command to set/change the password.
b. Add as many users as you want using adduser command and set password for them using passwd command.
Syntax: adduser <username>
c. On CentOS, the members of the wheel group get sudo privileges by default. So to grant a user the sudo access, use the usermod command to add that user to the wheel group.
Syntax: usermod -aG wheel <username>
Note: -a to append the user to the GROUPS mentioned by the -G option, without removing the user from other groups)
d. As shown above, switch to the new user using su command, and test the sudo privilege by running some commands.
e. Now the user02 can create other user accounts. No need to login as root. For example, to create a new user ‘user01’..
[user02@localhost
]$ sudo adduser user01
[user02@localhost
]$ sudo passwd user01
[user02@localhost
]$ sudo usermod -aG wheel user01
[user02@localhost
]$ sudo su — user01
[user01@localhost
f. Finally, if you want to change the hostname, issue below command.
$ sudo hostnamectl set-hostname <your-new-hostname>
Restart is required to apply the change. Issue one of the below commands.
$ shutdown -r
$ init 6
$ systemctl reboot
Step 7: Check Internet Connectivity in VM
Note: If you enabled and configured the the network during installation, you should have have internet connectivity within VM by now.
a. Use curl command to open some web URL. For example,
$ curl www.google.com
curl: (6) Could not resolve host: www.google.com; Unknown error
b. If it shows any error as shown above, probably the network was not correctly configured during the installation (Refer to Step 5, d). Follow the below steps to configure the network now. If curl worked successfully, then you can skip the steps below.
c. Identify the available networks interfaces using nmcli command.
[user01@localhost
]$ nmcli d
I found mine as enp0s3. Your’s might be different.
d. Open the network interface configuration file for the device found above. Config files are located in /etc/sysconfig/network-scripts/ directory.
[user01@localhost
]$ sudo vi /etc/sysconfig/network-scripts/ifcfg-enp0s3
e. Update the two parameters as given below and save the file.
BOOTPROTO=”dhcp”
ONBOOT=”yes”
f. Restart network service via systemctl command.
[user01@localhost
]$ sudo systemctl restart network
g. Now test the internet connectivity again using curl command. You should be able to reach the URL now.
[user01@localhost
Step 8: SSH Connection to VM Using PuTTY
a. Close the VM (Power off), if it is running.
b. By default, VM uses the NAT to attach to the host’s network. NAT is a type of internal network that allows outbound connections for browsing the Web, downloading files, and viewing email etc. You can see this in Network Settings.
c. Go to ‘Adapter 2’ tab and tick ‘Enable Network Adapter’. Select Attached to: ‘Host-only adapter’ from the drop-down list. Click OK.
Note: Host-only adapter creates a virtual network interface on the host to facilitate the connectivity among virtual machines and the host.
d. Start the VM. After logging in, check the IP address using ifconfig command.
Note: Ifconfig might not be available in minimal installation. We can install it using:[user01@localhost
]$ sudo yum –y install net-tools
f. From the ifconfig command output, note down the IP address of your VM. I found mine as 192.168.56.104, as shown below.
g. Now open PuTTY, and add new session configuration to connect to our VM.
Note: If you don’t have PuTTY, install it from here
h. Click ‘Open’ to start a new session to our VM. Hurrah.. I am able to login. 🙂
i. Now we can minimize the VirtualBox window and run all commands from PuTTY terminal.
Note: We cannot SSH to a user account (from PuTTY or by any means) that doesn’t have a password set. This is because of the default SSH configuration which can be overridden by updating the parameter PermitEmptyPasswords to “yes” in /etc/ssh/sshd_config and restarting the sshd service.
Tip: When you start the VM next time, click on the small arrow at the right side of the ‘Start’ button, and select ‘Detachable Start’ . This will start the VM with a window, but you can close that window to run the VM in background. By this way we can get rid of that ‘sometimes annoying’ window while we do all the work from PuTTY terminal.
Normal Start: VM starts with a window. Closing this window turns off the VM.
Detachable Start: VM‘s window can be closed without turning off the VM. We can choose ‘continue running in background’ when closing the window.
Headless Start: VM starts without a window. A small preview of the VM can be seen on the main window. To disable this preview, right click on the preview area and choose ‘Update disabled’.
CentOS as a Guest OS in VirtualBox
Installation of CentOS as a guest OS is much like installing on real hardware. Start by downloading the ISO file[s] you wish to use for installation from a CentOS Mirror.
Creating a Virtual Machine
Create a New Virtual Machine (VM) with the Virtual Machine Wizard, choosing Linux for the OS Type and Red Hat or Red Hat (64 bit) for the Operating System. Memory should be at least 768MB for a graphical install to work. Next the virtual hard disk wizard will start. The OS disk should be at least 8GB. For a relatively full install, allocate at least 15GB, otherwise use all the defaults. Additional disk[s] can be added later if desired.
After the VM is created, run Settings, go to Storage, and under IDE Controller click on the CD icon on the left, then select the similar CD icon on the right and pick Choose a virtual CD/DVD from the list. Navigate to the directory where the ISO image[s] reside and pick one, for example CentOS-6.7-x86_64-LiveDVD.iso or CentOS-7-x86_64-DVD-1511.iso. Change any additional settings, such as the amount of memory for the virtual video adapter, and whether to use NAT or Bridged networking. For a first install attempt make a minimum of changes to the defaults.
Start the VM and perform a graphical install, or if desired a text install. After the install reboot and perform firstboot configuration.
Installing Guest Additions
You will need to be the root user for the following tasks. Login to a root shell or «su -» in a terminal window.
The installation of VB will require the building of kernel modules. If DKMS (Dynamic Kernel Module Support) is installed it will be used and will simplify kernel upgrades. Installing DKMS from the EPEL repository is recommended before installing VirtualBox. Don’t forget to configure the yum-priorities plugin. Installing DKMS may pull in required development dependencies, depending on the package source.
If DKMS is not used the Guest Additions will need to be reinstalled after every kernel update.
If the development environment and kernel source are not already installed:
You may also choose to only install a minimum set of individual development tool packages (at least gcc and make are required, in addition to kernel-devel) rather than the groupinstall which some may consider overkill. Replace «kernel-devel» with «kernel-PAE-devel» if using a PAE kernel on CentOS-5. If you are not using a standard CentOS kernel, you must acquire and install the source for your kernel from wherever you got the kernel. Do not try to install a Xen kernel in a Guest OS, or run KVM or any other nested virtualization hypervisor.
From the VM Devices menu select Install Guest Additions. . If running a GUI the virtual CD image for guest additions will automount — for instance under CentOS-6 with KDE it is mounted under /media/VBOXADDITIONS_5.0.14_105127. If autorun is enabled in a GUI you may get a window asking if you want to let the autorun execute, and asking for root authorization. Take all the defaults and the install should complete.
If not in a GUI, or if there is no autorun, as root mount /dev/cdrom or /dev/sr0 (if necessary) and cd to the mountpoint. Type ./VBoxLinuxAdditions.run to install.
Patch for specific CentOS version
Usually after a point release, which introduces major changes to the kernel or other subsystems, the compilation of the vBox tools fails. When such issues arise we will try to post applicable patches here, until this issue is fixed by vBox.
This page created by PhilSchaffner. Wiki contributors are invited to make corrections, additions, or modifications.
HowTos/Virtualization/VirtualBox/CentOSguest (последним исправлял пользователь анонимно 2019-12-09 09:11:13)
Как установить CentOS в VirtualBox. Полная пошаговая инструкция
Познакомиться с возможностями операционной системы CentOS вы можете, установив ее в VirtualBox на ПК под управлением Windows 7, 10; macOS или другого дистрибутива Linux.
Что надо знать перед установкой
- Самой свежей версией на момент написания стать является CentOS 8.0 (1905), выпущенная 24 сентября 2019 года.
- Предполагается, что перед началом установки VirtualBox уже есть на вашем ПК. Ранее я подробно рассмотрел создание и настройку виртуальной машины.
- ОС предназначена для компьютеров с процессорами Intel, AMD и VIA.
- Потребуется соединение с интернетом, поскольку часть файлов в процессе установки будет загружаться из Сети.
Как скачать CentOS

Щелкните по кнопке «CentOS Linux DVD ISO» и стартует загрузка образа операционной системы. Вы можете также скачать ее с торрента.

Список зеркал предлагается по ссылке. В зависимости от особенностей вашего интернет-соединения, прямая загрузка может быть недоступна. В этом случае вам останется только воспользоваться торрентом.

Что нужно для установки системы
- ПК с 64-битным процессором (для CentOS 7 и 8). 32-битные процессоры поддерживаются версией CentOS 6.10.
- Не менее 1 гигабайт ОЗУ. Рекомендуется 1 гигабайт ОЗУ на каждое ядро ЦП.
- Не менее 10 гигабайт на жестком диске (лучше 20 гигабайт).
Формат установочных файлов
Дистрибутив CentOS основан на Red Hat Enterprise Linux. Для установки софта в CentOS применяются пакеты RPM (Red Hat Package Manager).
Предпочитаете дистрибутивы на основе Debian (DEB)?
Я подробно рассмотрел процесс установки в VirtualBox:
Как создать виртуальную машину
Откройте VirtualBox и нажмите расположенную на панели под строкой меню кнопку «Создать».

Создавая виртуальную машину и выделяя ей аппаратные ресурсы, используйте кнопку «Далее» для перехода к следующему экрану, «Назад» — для возврата к предыдущему.

В поле «Имя» введите название нового «виртуального компьютера». «Тип»: Linux; «Версия»: Red Hat.

Выделение ОЗУ и виртуальный жесткий диск для CentOS
Установите объем оперативной памяти не менее 2048 мегабайт. Это сделает работу с ОС более комфортной.

По умолчанию предусмотрена опция «Создать новый виртуальный жесткий диск». Не меняйте ее. Нажмите «Создать».

Если вы не планируете использовать создаваемый «диск» с другими инструментами виртуализации, оставьте тип накопителя «VDI».

Если вы укажете в качестве формата хранения «Динамический виртуальный жесткий диск», пространство на накопителе будет использоваться по мере необходимости. Если вы выберете «Фиксированный виртуальный жесткий диск», указанный вами объем предоставляется виртуальной машине сразу и станет недоступен вам для других задач. Фиксированный жесткий диск обычно быстрее, поэтому при наличии свободного пространства на HDD или SSD отдайте предпочтение этому варианту.

Укажите имя и размер виртуального жесткого диска. Если «железо» вашего ПК позволяет, рекомендую предоставить виртуальному накопителю не менее 20 гигабайт. Нажмите «Создать».

Настройка виртуальной машины
Новый «виртуальный ПК» отобразится в списке после ранее созданных вами.

Выделите ее и нажмите щелкните по кнопке «Настроить», расположенной на панели под строкой меню.

В разделе «Общие» на вкладке «Дополнительно» в полях «Общий буфер обмена» и «Функция Drag’n’Drop» выберите из списков «Двунаправленный». Это необходимо для обмена данными между основной ОС и CentOS, которую вы установите на виртуальную машину.

В разделе «Система» на вкладке «Материнская плата» определите порядок загрузки. Приоритетный: «Оптический накопитель (CD/DVD)»; второй: «Жесткий диск». Снимите «птички» возле других накопителей. Для изменения порядка загрузки используйте стрелки «Вверх» и «Вниз».

На вкладке «Процессор» определите число доступных виртуальной машине ядер ЦП. Рекомендую менее двух не указывать.

В разделе «Дисплей» на вкладке «Экран» предоставьте виртуальной машине видеопамять. Чем больше объем, тем выше качество изображения и удобнее работа с операционной системой. Нажмите «ОК».

Подготовка к установке CentOS на виртуальную машину
Выделите виртуальную машину. Предусмотрены два способа запустить ее:
- Двойным щелчком мышью по ней
- Нажатие кнопки «Запустить» на панели под строкой меню

Укажите путь к ранее загруженному файлу ISO-образа CentOS.
Не забудьте подписаться на наш Дзен

Нажмите кнопку «Продолжить» в нижней части диалогового окна.

Выберите пункт «Install CentOS Linux 8.0.1905». Если вы устанавливаете другую версию ОС, строка будет несколько отличаться.

Подождите, пока дистрибутив готовится к установке.

Выберите язык мастера установки ОС. Нажмите «Продолжить».

Актуальная раскладка клавиатуры отображается в верхнем правом углу окна установщика CentOS. Для переключения раскладки щелкните один раз щелкните по ней левой кнопкой мыши.

Часовой пояс и сетевое соединение
Некоторые секции окна «Обзор установки» отмечены оранжевым треугольником с восклицательным знаком. Заполните их.

В данном случае вам предлагается разбить диск на разделы. Оставьте предложенный установщиком вариант «Автоматически». Нажмите кнопку «Готово» в верхнем левом углу окна.

Перейдите в секцию «Time & Date» и выберите свой часовой пояс.

По умолчанию соединение с интернетом отключено.

В секции «Сеть и имя хоста» переведите ползунок активации сетевого соединения во включенное состояние. «Готово».

Создание учетной записи администратора
Нажмите расположенную в правом нижнем углу кнопку «Начать установку».

В окне конфигурации:

— Обратите внимание на подсказку мастера установки в нижней части окна.

— Дождитесь завершения загрузки пакетов, установки и настройки компонентов. Может потребоваться 30 и более минут.

— Создайте аккаунт пользователя и пароль администратора системы.

Щелкните левой кнопкой мыши по секции «Root Password». Введите пароль и подтвердите его во втором поле. Учетная запись администратора нужна для управления системой. Одинарный щелчок по кнопке «Готово».
Если установщик сочтет пароль ненадежным, он предложит пользователю подтвердить свое решение двойным щелчком левой кнопки мышью по кнопке «Готово». Причина недовольства мастера установки паролем будет указана на оранжевом фоне в нижней части окна.

Создание учетной записи пользователя
В разделе «Создание пользователя» введите в соответствующих полях полное имя, имя пользователя и пароль пользовательской учетной записи. Пароль подтвердите вводом в дополнительное поле.

Вы можете сделать этого пользователя администратором. Имя пользователя может содержать до 32 знаков без пробелов. Определите, нужно ли вводить пароль при вхоже в систему. Если посторонние не имеют доступа к компьютеру, снимите «птичку» слева от этой опции. Один раз щелкните левой кнопкой мыши по кнопке «Готово». Если мастер установки будет недоволен надежностью пароля, но вас он устраивает, подтвердите выбор двойным щелком по «Готово».

После появления в нижней части окна конфигурации сообщения об успешной установке CentOS, нажмите кнопку «Завершить настройку».

Подготовка к первому запуску CentOS
Будут произведены необходимые автоматические настройки. Перед началом работы с операционной системой:
- Необходимо принять условия лицензионного соглашения. Для этого поставьте «птичку» в белом квадратном блоке, расположенном ниже текста
- Введите пароль учетной записи пользователя, если вы оставили включенной опцию подтверждения входа в систему вводом пароля
- Выберите язык рабочего стола и раскладку клавиатуры
- Включите или отключите для приложений возможность определения местоположения
- Возможно сразу же ввести данные своих учетных записей:
- Nextcloud
- Microsoft
Пятый шаг вы можете пропустить и вернуться к нему после того, как будете уверены, что CentOS вам подходит.