CentOS Linux on Hyper-V – The Complete Guide

Save to My DOJO

CentOS Linux on Hyper-V – The Complete Guide

Note: This article was originally published on May 2017. It has been fully updated to be current as of August 2019.

Microsoft continues turning greater attention to Linux. We can now run PowerShell on Linux, we can write .Net code for Linux, we can run MS SQL on Linux, Linux containers will run natively in Windows containers… the list just keeps growing. Linux-on-Hyper-V has featured prominently on that list for a while now, and the improvements continue to roll in.

Microsoft provides direct support for Hyper-V running several Linux distributions as well as FreeBSD. If you have an organizational need for a particular distribution, then someone already made your choice for you. If you don’t have such a mandate, you might need to make that decision yourself. I’m not a strong advocate for any particular distribution. I’ve written in the past about using Ubuntu Server as a guest. However, there are many other popular distributions available and I like to branch my knowledge.

Why Choose CentOS?

I’ve been using Red Hat’s products off and on for many years and have some degree of familiarity with them. At one time, there was simply “Red Hat Linux”. As a commercial venture attempting to remain profitable, Red Hat decided to create “Red Hat Enterprise Linux” (RHEL) which you must pay to use. With Red Hat being sensitive to the concept of free (as in what you normally think of when you hear “free”) being permanently attached to Linux in the collective conscience, they also make most of RHEL available to the CentOS Project.

One of the reasons that I chose Ubuntu was its ownership by a commercial entity. That guarantees that if you’re ever really stuck on something, there will be at least one professional organization that you can pay to assist you. CentOS doesn’t have that kind of direct backing. However, I also know from experience that relatively few administrators ever call for operating system support. The ones that will make such a call tend to work for bigger organizations that pay for RHEL or the like. The rest will call some sort of service provider, like a local IT outsourcer. With that particular need mitigated, CentOS has these strengths:

  • CentOS is based on RHEL. This is not a distribution that someone assembles in their garage (not that I have any personal opposition to such an endeavor, but almost every organization places a premium on stability and longevity in their suppliers)
  • CentOS has wide community support and familiarity. You can easily find help on the Internet. You will also not struggle to find support organizations that you can pay for help.
  • CentOS has a great deal in common with other Linux distributions. Because “Linux” is really just a kernel, and an open-source one at that, it’s theoretically possible for a distribution to completely change everything about it and build a completely unique operating system and environment. In practice, no one does. That means that the bulk of knowledge you have about any other Linux distribution is applicable to CentOS.

That hits the major points that will assure most executives that you’re making a wise decision. In the scope of Hyper-V, Microsoft’s support list specifically names CentOS.

Stable, Yet Potentially Demanding

When you use Linux’s built-in tools to download and install software, you work from approved repositories. Essentially, that means that someone decided that a particular package adequately measured up to a standard. Otherwise, you’d need to go elsewhere to acquire that package.

The default CentOS repositories are not large when compared to some other distributions. They do not contain recent versions of many common packages, including the Linux kernel. However, the versions offered in the CentOS repositories are known to be solid and stable. If you want to use more recent versions, then you’ll need to be(come) comfortable manually adding repositories and/or acquiring, compiling, and installing software.

No GUIs Here

CentOS does make at least one GUI available, but I won’t cover it. I don’t know if CentOS’s GUI requires 3D acceleration the way that Ubuntu’s does. If it does, then the GUI experience under Hyper-V would be miserable. However, I didn’t even attempt to use any CentOS GUIs because they’re really not valuable for anything other than your primary use desktop. If you’re new to Linux and the idea of going GUI-free bothers you, then take heart: Linux is a lot easier than you think it is. I don’t feel that any of the Linux GUIs score highly enough in the usability department to meaningfully soften the blow of transition anyway.

If you’ve already read my Ubuntu article, then you’ve already more or less seen this bit. Linux is easy because pretty much everything is a file. There are only executables, data, and configuration files. Executables can be binaries or text-based script files. So, any time you need to do anything, your first goal is to figure out what executable to call. Configuration files are almost always text-based, so you only need to learn what to set in the configuration file. The Internet can always help out with that. So, really, the hardest part about using Linux is figuring out which executable(s) you need to solve whatever problem you’re facing. The Internet can help out with that as well. You’re currently reading some of that help.

Enough talk. Let’s get going with CentOS.

Downloading CentOS

You can download CentOS for free from www.centos.org. As the site was arranged on the day that I wrote this article, there was a “Get CentOS” link in the main menu at the top of the screen and a large orange button stamped “Get CentOS Now” after the introductory text. From either of those, you reach a page with a few packaging options. I chose “DVD ISO” and used it to write this article. I would say that if you have a Torrent application installed, choose that option. It took me quite a bit of hunting to find a fast mirror.

For reference, I downloaded CentOS-7-x86_x64-DVD-1810.iso.

How to Build a Hyper-V Virtual Machine for CentOS

There’s no GUI and CentOS is small, so don’t create a large virtual machine. These are my guidelines:

  • 2 vCPUs, no reservation. All modern operating systems work noticeably better when they can schedule two threads as opposed to one. You can turn it up later if you’re deployment needs more.
  • Dynamic Memory on; 512MB startup memory, 256MB minimum memory, 1GB maximum memory. You can always adjust Dynamic Memory’s maximum upward, even when the VM is active. Start low.
  • 40GB disk is probably much more than you’ll ever need. I use a dynamically expanding VHDX because there’s no reason not to. The published best practice is to create this with a forced 1 megabyte block size, which must be done in PowerShell. I didn’t do this on my first several Linux VMs and noticed that they do use several gigabytes more space, although still well under 10 apiece. I leave the choice to you.
  • I had troubles using Generation 2 VMs with Ubuntu Server, but I’m having better luck with CentOS. If you use Generation 2 with your CentOS VMs on Hyper-V 2012 R2/8.1 or earlier, remember to disable Secure Boot. If using 2016, you can leave Secure Boot enabled as long as you select the “Microsoft Certification Authority”.
  • If your Hyper-V host is a member of a failover cluster and the Linux VM will be HA, use a static MAC address. Linux doesn’t respond well when its MAC addresses change.

The following is a sample script that you can modify to create a Linux virtual machine in Hyper-V: You can find a more polished edition in my GitHub repository.

#function New-LinuxVM {
	#requires -Modules Hyper-V
	[CmdletBinding(SupportsShouldProcess=$true)]
	param
	(
		[Parameter(Mandatory=$true, Position=1)][String]$VMName,
		[Parameter()][String]$VHDXName = '',
		[Parameter()][String]$VMStoragePath = '',
		[Parameter()][String]$VHDStoragePath = '',
		[Parameter()][String]$InstallISOPath = '',
		[Parameter()][Switch]$Cluster,
		[Parameter()][String]$VMSwitchName = '',
		[Parameter()][Uint32]$StartupMemory = 512MB,
		[Parameter()][Uint32]$MinimumMemory = 256MB,
		[Parameter()][Uint32]$MaximumMemory = 1GB,
		[Parameter()][Uint64]$VHDXSizeBytes = 40GB
	)

	if([String]::IsNullOrEmpty($VHDXName))
	{
		$VHDXName = '{0}.vhdx' -f $VMName
	}
	if($VHDXName -notmatch '.vhdx$')
	{
		$VHDXName += '.vhdx'
	}
	if([String]::IsNullOrEmpty($VMStoragePath))
	{
		$VMStoragePath = (Get-VMHost).VirtualMachinePath
	}
	if(-not (Test-Path -Path $VMStoragePath))
	{
		Write-Error -Message ('VM path {0} does not exist.' -f $VMStoragePath)
		return
	}
	if([String]::IsNullOrEmpty($VHDStoragePath))
	{
		$VHDStoragePath = (Get-VMHost).VirtualHardDiskPath
	}
	if(-not (Test-Path -Path $VHDStoragePath))
	{
		Write-Error -Message ('Storage path {0} does not exist.' -f $VHDStoragePath)
		return
	}
	$VHDStoragePath = Join-Path -Path $VHDStoragePath -ChildPath $VHDXName
	if([String]::IsNullOrEmpty($InstallISOPath) -or -not (Test-Path -Path $InstallISOPath -PathType Leaf))
	{
		Write-Error -Message ('ISO {0} does not exist' -f $InstallISOPath)
		return
	}
	if([String]::IsNullOrEmpty($VMSwitchName))
	{
		$VMSwitchName = (Get-VMSwitch | ? SwitchType -eq 'External')[0].Name
	}
	if([String]::IsNullOrEmpty($VMSwitchName))
	{
		Write-Error -Message ('No virtual switch specified')
		return
	}

	$VM = New-VM -Name $VMName -MemoryStartupBytes $StartupMemory -SwitchName $VMSwitchName -Path $VMStoragePath -Generation 2 -NoVHD
	Set-VMMemory -VM $VM -DynamicMemoryEnabled $true -MinimumBytes $MinimumMemory -MaximumBytes $MaximumMemory
	Set-VMProcessor -VM $VM -Count 2
	Start-VM -VM $VM
	Stop-VM -VM $VM -Force
	New-VHD -Path $VHDStoragePath -SizeBytes $VHDXSizeBytes -Dynamic -BlockSizeBytes 1MB
	$VMVHD = Add-VMHardDiskDrive -VM $VM -ControllerType SCSI -ControllerNumber 0 -ControllerLocation 0 -Path $VHDStoragePath -Passthru
	$VMDVDDrive = Add-VMDvdDrive -VM $VM -ControllerNumber 0 -ControllerLocation 1 -Passthru
	$VMNetAdapter = Get-VMNetworkAdapter -VM $VM
	Set-VMNetworkAdapter -VMNetworkAdapter $VMNetAdapter -StaticMacAddress ($VMNetAdapter.MacAddress)
	Set-VMFirmware -VM $VM -BootOrder $VMDVDDrive, $VMVHD, $VMNetAdapter -EnableSecureBoot On -SecureBootTemplate 'MicrosoftUEFICertificateAuthority'
	Set-VMDvdDrive -VMDvdDrive $VMDVDDrive -Path $InstallISOPath
	if($Cluster)
	{
		Add-ClusterVirtualMachineRole -VMName $VMName
	}
#}

If you’re going to use this a lot, consider modifying the parameter defaults to your liking. For instance, you’re probably not going to move your install ISO often.

You could also use your first installation as the basis for a clone. Use a generic name for the VM/VHDX if that’s your plan.

A Walkthrough of CentOS Installation

When you first boot, it will default to Test this media & install CentOS 7. I typically skip the media check and just Install CentOS Linux 7.

installing CentOS

It will run through several startup items, then it will load the graphical installer. Choose your language:

CentOS 7 installer

After selecting the language, you’ll be brought to the Installation Summary screen. Wait a moment for it to detect your environment. As an example, the screen initially shows Not Ready for the Security Policy. It will change to No profile selected once it has completed its checks.

CentOS Installation Destination

You can work through the items in any order. Anything without the warning triangle can be skipped entirely.

I start with the NETWORK & HOST NAME screen as that can have bearing on other items. When you first access the screen, it will show Disconnected because it hasn’t been configured yet. That’s different behavior from Windows, which will only show disconnected if the virtual network adapter is not connected to a virtual switch.

CentOS network and host name

If you’ll be using DHCP, click the Off slider button at the top right for it to attempt to get an IP. If that works, it will automatically switch to On and display the acquired IP address. For static or advanced configuration, click the Configure. I’ve shown the IPv4 Settings tab. You can type out the full octet mask instead of the CIDR shortcut, if you prefer. Fill out this tab, and/or the others, as necessary.

IPv4 settings

Don’t forget to change the host name at the lower left of the networking screen and Apply it before clicking Done to leave this screen.

After you’ve set up networking, set the DATE & TIME. If it can detect a network connection, you’ll be allowed to set the Network Time slider to On. Configure as desired.

CentOS date and time

You must click into the Installation Destination screen or the installer will not allow you to proceed. By default, it will select the entirety of the first hard drive for installation. It will automatically figure out the best way to divide storage. You can override it if you like. If you’re OK with defaults, just click Done.

CentOS installation destination

Explore the other screens as you desire. I don’t set anything else on my systems. At this point, you have handled all the required and can click Begin Installation.

installation summary

While the system installs, you’ll be allowed to set the root password and create the initial user.configuration

As you enter the password for root, the system will evaluate its strength. If it decides that the password you chose isn’t strong enough, you’ll be forced to click Done twice to confirm. The root account is the rough equivalent of the Administrator account on Windows, so do take appropriate steps to secure it with a strong password and exercise care in the keeping of that password.

root password

The user creation screen is straightforward. It has the same password-strength behavior as the root screen.

create user

Now just wait for the installation to complete. Click Finish Configuration if prompted. Once the installation completes, it will present a Reboot button. Click when ready.

The system will restart and bring you to the login screen of a completely installed CentOS virtual machine:

CentOS Linux 7 virtual machine

Assuming that you created a named user for yourself and made it administrator, log in with that account. Otherwise, you can log in as root. It’s poor practice to use the root account directly, and even worse to leave the root account logged in.

CentOS Post-Install Wrap-Up for Hyper-V

I have a bit of a chicken-and-egg problem here. You need to do a handful of things to wrap-up, but to do that easily, it helps to know some things about Linux. If you already know about Linux, this will be no problem. Otherwise, just follow along blindly. I’ll explain more afterward. CentOS doesn’t need much, fortunately.

To make this a bit easier, you might want to wait until you’ve met PuTTY. It allows for simple copy/paste actions. Otherwise, you’ll need to type things manually or use the Paste Clipboard feature in the Hyper-V VMCONNECT window. Whatever you choose, just make sure that you follow these steps sooner rather than later.

1. Install Nano

Editing text files is a huge part of the Linux world. It’s also one of the most controversial, bordering on zealotry. “vi” is the editor of choice for a great many. Its power is unrivaled; so is its complexity. I find using vi to be one of the more miserable experiences in all of computing, and I refuse to do it when given any choice. Conversely, the nano editor is about as simple as a text-editing tool can be in a character mode world and I will happily use it for everything. Install it as follows:

sudo yum install -y nano

The command is case-sensitive and you will be prompted for your password if not logged in as root.

2. Enable Dynamic Memory In-Guest

You need to enable the Hot Add feature to use Dynamic Memory with CentOS.

Start by creating a “rules” file. The location is important (/etc/udev/rules.d) but the name isn’t. I’ll just use the same one from Microsoft’s instructions:

sudo nano /etc/udev/rules.d/100-balloon.rules

You may be prompted for your password.

You’ll now be looking at an empty file in the nano editor. Type or paste the following:

SUBSYSTEM=="memory", ACTION=="add", ATTR{state}="online"

Now press [CTRL]+[X] to exit, then press [Y] to confirm and [Enter] to confirm the filename.

At next reboot, Dynamic Memory will be functional.

3. Install Extra Hyper-V Tools

Note: the daemons ship directly in 18.10, so you can probably skip this step.

Most of the tools you need to successfully run Linux on Hyper-V are built into the CentOS distribution. There are a few additional items that you might find of interest:

  • VSS daemon (for online backup)
  • File copy daemon so you can use PowerShell to directly transfer files in from the host
  • KVP daemon for KVP transfers to and from the host

To install them:

sudo yum install -y hyperv-daemons

4. Change the Disk I/O Scheduler

By default, Linux wants to help optimize disk I/O. Hyper-V also wants to optimize disk I/O. Two optimizers are usually worse than none. Let’s disable CentOS’s.

You must be root for this.

su root

You’ll be prompted for the root password.

echo noop > /sys/block/sda/queue/scheduler
exit

The above will change the scheduler to “noop”, which means that CentOS will not attempt to optimize I/O for the primary hard disk. “exit” tells CentOS to exit from the root login back to your login.

Credit for the echo method goes to the authors at nixCraft.

10 Tips for Getting Started with CentOS Linux on Hyper-V

This section is for those with Windows backgrounds. If you already know Linux, you probably won’t get anything out of this section. I will write it from the perspective of a seasoned Windows user. Nothing here should be taken as a slight against Linux.

1. Text Acts Very Differently

Above all, remember this: Linux is CaSE-SENsiTiVe.

  • yum and Yum are two different things. The first is a command. The second is a mistake.
  • File and directory names must always be typed exactly.

Password fields do not echo anything to the screen.

2. Things Go the Wrong Way

In Windows, you’re used to C: drives and D: drives and SMB shares that start with \.

In Linux, everything begins with the root, which is just a single /. Absolutely everything hangs off of the root in some fashion. You don’t have a D: drive. Starting from /, you have a dev location, and drives are mounted there. For the SATA virtual drives in your Hyper-V machine, they’ll all be sda, sdb, sdc, etc. So, /dev/sdb would be the equivalent to your Windows D: drive. Usually, we use mount points instead of accessing files and folders from their hardware-based root. So, when you retrieve a listing of the root directory, the items you see could exist on more than one drive.

Partitions are just numbers appended to the drive. sda1, sda2, etc.

Directory separators are slashes (/) not backslashes (). A directory that you’ll become familiar with is usr. It lives at /usr.

Moving around the file system should be familiar, as the Windows command line uses similar commands. Linux typically uses ls where Windows uses dir, but CentOS accepts dir. cd and mkdir work as they do on Windows. Use rm to delete things. Use cp to copy things. Use mv to move things. Also use mv to rename things.

You cannot run an executable in the same folder just by typing its name and pressing [Enter], as in the Windows command processor. PowerShell behaves the same way, so that may not be strange to you. Use dot and slash to run a script or binary in the same folder:

./scriptfile

Linux doesn’t use file extensions. Instead, it uses attributes. So, if you create the equivalent of a batch file and then try to execute it, Linux won’t have any idea what you want to do. You need to mark it as executable first. Do so like this:

chmod +x ./thatscriptfileyouwanttouse

As you might expect, -x removes the executable attribute.

The default Linux shell does have tab completion, but it’s not the same as what you find on Windows. It will only work for files and directories, for starters. Second, it doesn’t cycle through possibilities the way that PowerShell does. The first tab press works if there is only one way for the completion to work. A second tab press will show you all possible options. You can use other shells with more power than the default, although I’ve never done it.

3. Quick Help is Available

Most commands and applications have a -h and/or a –-help parameter that will give you some information on running them. –help is often more detailed than -h. You can sometimes type  man commandname  to get other help (“man” is short for “manual”). It’s not as consistent as PowerShell help, mostly because each executable and script author must come up with their own help text. Also, PowerShell’s designers got to work with the benefits of hindsight and rigidly controlled design and distribution.

4. You Can Go Home

You’ve got your own home folder, which is the rough equivalent of the “My Documents” folder in Windows. It’s at the universal alias ~. So, cd ~  takes you to your home folder. You can reference files in it with ~/filename.

5. Boss Mode

“root” is the equivalent of “Administrator” on Windows. But, the account you made has nearly the same powers — although not exactly on demand. You won’t have root powers until you specifically ask for them with “sudo”. It’s sort of like “Run as administrator” in Windows, but a lot easier. In fact, the first time you use sudo, the intro text tells you a little bit about it:

centos_sudo

So basically, if you’re going to do something that needs admin powers, you just type “sudo” before the command, just like it says. The first time, it will ask for a password. It will remember it for a while after that. However, 99% of what I do is administrative stuff, so I pop myself into a sudo session that persists until I exit, like this:

sudo -s

You’ll have to enter your password once, and then you’ll be in sudo mode. You can tell that you’re in sudo mode because the dollar sign in te prompt will change to a hash sign:

centos_sudos

I only use Linux for administrative work, so I always use the account with my name on it. However, even when it’s not in sudo mode, it’s still respected as an admin-level account. If you will be using a Linux system as your primary (i.e., you’ll be logged in often), create a non-administrative account to use. You can flip to your admin account or root anytime:

su eric

Always respect the power of these accounts.

6. “Exit” Means Never Having to Say Goodbye

People accustomed to GUIs with big red Xs sometimes struggle with character mode environments. “exit” works to end any session. If you’re layered in, as in with sudo or su, you may need to type “exit” a few times. “logout” works in most, but not all contexts.

7. Single-Session is for Wimps

One of the really nifty things about Linux is multiple concurrent sessions. When you first connect, you’re in terminal 1 (tty1). Press [Alt]+[Right Arrow]. Now you’re in tty2! Keep going. 6 wraps back around to 1. [Alt]+[Left Arrow] goes the other way.

You need to be logged in to determine which terminal you’re viewing. Just type tty.

8. Patches, Updates, and Installations, Oh My.

Pretty much all applications and OS components are “packages”. “yum” and “rpm” are your package managers. They’re a bit disjointed, but you can usually find what you need to know with a quick Internet search.

Have your system check to see if updates are available (more accurately, this checks the version data on download sources):

sudo yum check-update

Install package patches and upgrades:

sudo yum update

There’s also an “upgrade” option which goes a bit further. Update is safer, upgrade gets more.

Show all installed packages that yum knows about:

sudo yum list

The rpm tool shows different results, but for my uses yum is sufficient.

Find a particular installed package, in this case, “hyperv” (spelling/case counts!):

sudo yum list installed | grep hyperv

Look for available packages:

sudo yum list unzip<br>

Install something (in this case, the Apache web server):

sudo yum install httpd

9. System Control

CentOS’s equivalent to Task Manager is top. Type top at a command prompt and you’ll be taken right to it. Use the up and down arrows and page up and page down to move through the list. Type a question mark [?] to be taken to the help menu that will show you what else you can do. Type [Q] to quit.

10. OK, I’m Done Now

If you’ve used the shutdown command in Windows, then you’ll have little trouble transitioning to Linux. shutdown tells Linux to shut down gracefully with a 1-minute timer. All active sessions get a banner telling them what’s coming.

Immediate shutdown (my favorite):

shutdown now

Reboot immediately:

shutdown -r now

There’s an -H switch which, if I’m reading this right, does a hard power off. I don’t use that one.

[thrive_leads id=’17165′]

Useful Tools for CentOS Linux

Manipulating your CentOS environment from the VMConnect console will get tiring quickly. Here are some tools to make managing it much easier.

Text Editors

I already showed you nano. Just type nano at any prompt and press [Enter] and you’ll be in the nano screen. The toolbar at the bottom shows you what keypresses are necessary to do things, ex: [CTRL]+[X] to exit. Don’t forget to start it with sudo if you need to change protected files.

The remote text editing tool that I use is Notepad++. It is a little flaky — I sometimes get Access Denied errors with it that I don’t get in any other remote tool (setting it to Active mode seems to help a little). But, the price is hard to beat. If I run into real problems, I run things through my home folder. To connect Notepad++ to your host:

  1. In NPP, go to Plugins->NppFTP->Show NppFTP Window (only click if it’s not checked):
    NPP FTP Window Selector

    NPP FTP Window Selector

     

  2. The NppFTP window pane will appear at the far right. Click the icon that looks like a gear (which is, unfortunately, gray in color so it always looks disabled), then click Profile Settings:NPP FTP Profile Item
  3. In the Profile Settings window, click the Add New button. This will give you a small window where you can provide the name of the profile you’re creating. I normally use the name of the system.
    Add FTP Profile
  4. All the controls will now be activated.
    1. In the Hostname field, enter the DNS name or the IP address of the system you’re connecting to (if you’re reading straight through, you might not know this yet).
    2. Change the Connection type to SFTP.
    3. If you want, save the user name and password. I don’t know how secure this is. I usually enter my name and check Ask for password. If you don’t check that and don’t enter a password, it will assume a blank password.
      NPP FTP Profile

      NPP FTP Profile

       

  5. You can continue adding others or changing anything you like (I suggest going to the Transfers tab and setting the mode to Active). Click Close when ready.
  6. To connect, click the Connect icon which will now be blue-ish. It will have a drop-down list where you can choose the profile to connect to.NPP FTP Connect
  7. On your first connection, you’ll have to accept the host’s key:NPP Host Key
  8. If the connection is successful, you’ll attach to your home folder on the remote system. Double-clicking an item will attempt to load it. Using the save commands in NPP will save back to the Linux system directly.NPP FTP Directory

Remember that NPP is a Windows app, and as a Windows app, it wants to save files in Windows format (I know, weird, right?). Windows expects that files encoded in human-readable formats will end lines using a carriage-return character and a linefeed character (CRLF, commonly seen escaped as rn). Linux only uses the linefeed character (LF, commonly seen escaped as n). Some things in Linux will choke if they encounter a carriage return. Any time you’re using NPP to edit a Linux file, go to Edit -> EOL Conversion -> UNIX/OSX Format.

NPP EOL Conversion

NPP EOL Conversion

 

WinSCP

WinSCP allows you to move files back and forth between your Windows machine and a Linux system. It doesn’t have the weird permissions barriers that Notepad++ struggles with, but it also doesn’t have its editing powers.

  1. Download and install WinSCP. I prefer the Commander view but do as you like.
  2. In the Login dialog, highlight New Site and fill in the host’s information:WinSCP Profiles
  3. Click Save to keep the profile. It will present a small dialog asking you to customize how it’s saved. You can change the name or create folders or whatever you like.
  4. With the host entry highlighted, click Login. You’ll be prompted with a key on first connect:WinSCP Key
  5. Upon clicking Yes, you’ll be connected to the home folder. If you get a prompt that it’s listening on FTP, something went awry because the install process we followed does not include FTP. Check the information that you plugged in and try the connection again.
  6. WinSCP integrates with the taskbar for quick launching:WinSCP Taskbar

PuTTY

The biggest tool in your Linux-controlling arsenal will be PuTTY. This gem is an SSH client for Windows. SSH (secure shell) is how you remote control Linux systems. Use it instead of Hyper-V’s virtual machine connection. It’s really just a remote console. PuTTY, however, adds functionality on top of that. It can keep sessions and it gives you dead-simple copy/paste functionality. Highlight text, and it’s copied. Right-click the window, and it’s pasted at the cursor location.

  1. Download PuTTY. I use the installer package myself but do as you like.
  2. Type in the host name or IP address in that field.PuTTY Profiles
  3. PuTTY doesn’t let you save credentials. But, you can save the session. Type a name for it in the Saved Sessions field and then click Save to add it to the list. Clicking Load on an item, or double-clicking it, will populate the connection field with the saved details.
  4. Click Open when ready. On the first connection, you’ll have to accept the host key:PuTTY Key
  5. You’ll then have to enter your login name and password. Then you’ll be brought to the same type of screen that you saw in the console:PuTTY Console
  6. Right-click the title bar of PuTTY for a powerful menu. The menu items change based on the session status. I have restarted the operating system for the screenshot below so that you can see the Restart Session item. This allows you to quickly reconnect to a system that you dropped from… say, because you restarted it.PuTTY Menu
  7. PuTTY also has taskbar integration:PuTTY Taskbar
  8. When you’re all done, remember to use “exit” to end your session.

Your Journey Has Begun

From here, I leave you to explore your fresh new Linux environment. If you’d like, we have an article on using CentOS to host a Nagios environment for monitoring your Hyper-V environment.

Altaro Hyper-V Backup
Share this post

Not a DOJO Member yet?

Join thousands of other IT pros and receive a weekly roundup email with the latest content & updates!

459 thoughts on "CentOS Linux on Hyper-V – The Complete Guide"

  • This is terrific stuff. I’m getting more into Linux this year with the arrival of PowerShell to the open source world. I’d love to learn more about copying files between the Linux guest and Hyper-V host.

  • Conan says:

    RE: yum install hyperv-daemons

    Also need to enable it:
    systemctl enable hypervvssd hypervkvpd –now

    • Eric Siron says:

      Both of these services are already running on mine. What does this command do that isn’t already being done?
      Edit: They show up in the processes list, not as services. What’s the difference?

      • Justin Buckley says:

        Hi Eric,

        Thanks for this info! I’ve recently upgraded to Hyper-V 2016 and have been following this guide to setup my new CentOS 7.5 VMs. I was wondering if you ever answer the above question? I did notice that after running ‘yum install hyperv-daemons’, KVP showed as enabled on the Hyper-V host. I had put in some previous notes to also run the following:

        # systemctl enable hypervfcopyd
        # systemctl start hypervkvpd hypervvssd hypervfcopyd

        But as I’m a novice, are those commands even necessary? Or is the yum install and a reboot all that’s needed?

        • Eric Siron says:

          Do without, and reboot. If the services are running then you don’t need to do all that.
          Sorry but my test environment isn’t currently in a position for me to give you a definitive answer and I don’t want you to wait on me.

  • Dave Scarbrough says:

    Great article! We run a couple turnkeylinux(.com) appliances (Debian Jessie based) on H-V 2012 R2 Server, and they run flawlessly. The initial H-V tools are auto-recognized, but I wasn’t aware of the extra hyperv-daemons package. I guess that would be apt-get install hyperv-daemons in Debian. Also, PuTTY does work superbly to connect not just to *nix machines but also to switches, call managers, embedded appliances, all sorts of stuff. And for transferring files back and forth, FileZilla – just enter sftp://machine on port 22 and you’re in. Keep up the great work, Eric!

  • jassonmc says:

    Eric,

    I don’t get your statement:
    “I use a dynamically expanding VHDX because there’s no reason not to. The published best practice is to create this with a forced 1 megabyte block size, which must be done in PowerShell. I didn’t do this on my first several Linux VMs and noticed that they do use several gigabytes more space, although still well under 10 apiece. I leave the choice to you”

    Which block size do you mean? The one that defaults to 32mb on a default creation of a VHDX? Isn’t that block size only relevant to dynamic expansions of the VHDX. How does that impact the disk size by several GB?

    • Eric Siron says:

      Sorry for the confusing wording. I’ll fix that later.
      I mean: I always use dynamically-expanding VHDX. That hasn’t changed.
      On my first few Linux VMs, I didn’t know about setting the block size, so I left the 32MB default. I ended up with VHDXs that expanded out to as much as 10GB even though there was nothing but the base OS.
      Once I learned about the 1MB block setting, I started using that. Now my OS-only Linux VHDXs weigh in at less than 3GB.
      Truthfully, I’m not certain where the discrepancy comes from, but then I don’t know much about the various Linux filesystems, either. I read a glossed-over explanation that mentioned Linux’s sparse files. I don’t understand that explanation. If a filesystem tries to write an all-zero block to a dynamically-expanding disk and it would need to grow to accommodate that block, the VHDX driver will just ignore the write. So, I don’t know. But, you can see the differences, so something is going on.

  • jassonmc says:

    Strange, my fresh CentOS 7 minimal installations always require under 2GB on the VHDX and I use the Hyper-V GUI to create the disks. I’ll give it a try next time anyway with the smaller block size.

    Thanks anyway for the quick reply 😉

    • Eric Siron says:

      Huh… well, OK, I didn’t try the default specifically on CentOS. It was on Ubuntu that I had all of the overgrowth issues. Since the recommendation is for Linux in general and not for Ubuntu/Debian or anything like that, it seemed universally applicable.
      I notice that CentOS uses xfs by default where Ubuntu uses ext4. Maybe that’s the difference.

  • Alex says:

    Hello Eric,

    this is a really interesting article as we are using CentOS 7 on our Hyper-V host and are in need of the possibility to create live backups of this VM.

    In your article you say it will be possible to do a application consistent backup with Altaro without suspending the CentOS VM. is this correct?

    The Altaro support told me the opposite. They said it is only possible to create crash consistent live backups of Linux VM,s in general.

    Our Hyper-V Server is 2008R2
    VM CentOS 7.2 with up to date hyperv-daemon

    So, what is correct here now?

    Thanks

    • Eric Siron says:

      I didn’t go so far as to commit to application consistent. I’ll only go as far as online backup, meaning that backups do not need to save or pause a CentOS 7 VM with the vss component in order to back it up.
      I don’t know of any documentation for the VSS component on Linux, but “hyperv.h” does not expose any callbacks for the VSS writer. It looks like it freezes the file system, but I don’t see a way for an application to register to receive advance notification. If there is one, then application developers would need to hook that. Otherwise, crash consistent is the best you’ll get.

  • Ash says:

    Great work Eric! I am getting my hands dirty with Hyper-V and CentOS at the same time. Your article came in very handy.

  • Richard Vencu says:

    Hi,

    Having a Centos 7 inside a generation 2 VM under Hyper-V 2016 (hence configuration 8.0) I need to “downgrade” the configuration to 5.0 so I can move the machine to a Hyper-V 2012R2

    I know I need to create a new VM and attach the vhdx from the original machine but I am having some difficulties due to the EFI boot. I read somewhere how to copy the /boot/efi/EFI/centos folder into /boot/efi/EFI/BOOT folder and rename some files but it was meant for ubuntu and centos 6 that uses legacy grub. If you have a solution for centos 7 please share

    • Eric Siron says:

      Hi Richard,
      Unfortunately, I don’t know the answer either.
      I did some Googling, and couldn’t find any answer newer than what you already found.
      I would approach this as a “move hard drive to a new computer” or even a “cloning” problem. That might get better results. I’d consider starting a question thread on Stack Exchange: https://unix.stackexchange.com/

    • Hilton Travis says:

      This is what I do here on all my Centos 7.x VMs and it works a treat…

      1. Log in to the virtual machine.
      2. Change directory to the “boot EFI” directory: cd /boot/efi/EFI
      3. Copy the grubx64.efi file from “centos” to “BOOT”: sudo cp –r centos/grubx64.efi BOOT

      What this does is move the boot information out of the UEFI firmware and onto the disk.  With this done you can copy and boot the virtual hard drive with ease.

  • RichardFrank says:

    great article.
    the file /sys/block/sda/queue/scheduler contains
    noop anticipatory deadline [cfg]

    should I replace that with just noop

  • Athreya says:

    I have a question
    How do you add in com port or USB on to hyper-V with centos VM

  • Andrei says:

    Thanks for the article and providing all the details.
    I’ve tried with the latest CentOS version (CentOS-7-x86_64-DVD-1708.iso) and I can’t start it in Hyper-V on Windows 10. Neither as Generation 1 nor 2.

    Fortunately it worked with the image specified by you (CentOS-7-x86_64-DVD-1611.iso), as generation 2, with secure boot disabled.

  • Janro says:

    There are packages in base repo:
    hyperv-daemons-0-0.30.20161211git.el7.x86_64.rpm
    hyperv-daemons-license-0-0.30.20161211git.el7.noarch.rpm
    hyperv-tools-0-0.30.20161211git.el7.noarch.rpm
    hypervfcopyd-0-0.30.20161211git.el7.x86_64.rpm
    hypervkvpd-0-0.30.20161211git.el7.x86_64.rpm
    hypervvssd-0-0.30.20161211git.el7.x86_64.rpm

    And there is Linux Integration Services (https://www.microsoft.com/en-us/download/details.aspx?id=55106)

    Which one is better? What is the difference? I think I [should|can] not use both at the same time.

    I use LIS and I know that sometime the kernel is too new and LIS is not uptodate.

    • Eric Siron says:

      The standalone LIS predates the inclusion into the Linux kernel, so its existence is historical in nature. Today, it would best be used in distributions that deviate from the core Linux kernel by not including the LIS portions. It could also be used in instances where you were blocked from updating the kernel for some reason but not blocked from updating the LIS.
      Not sure that I could qualify “better” or “worse” in this case, though. If the functionality that I care about is there and the security is equivalent then I wouldn’t care about the version number. I generally go with the LIS from a distribution’s repository because that distribution’s maintainers would at least have the opportunity to tweak them if necessary and because updates won’t require a lot of manual intervention.

  • Peter says:

    Why didn’t you use the Hyper-V Manager to create a VM, but used some PowerShell script?

    • Eric Siron says:

      Because PowerShell does what Hyper-V Manager can’t, and once I’ve written a script I don’t have to slog through GUI screens anymore.

  • Jason says:

    Do you have an example of the VM creation script with the parameters filled in. I’m a super newbie and I’m not sure exactly what I’m supposed to put in each parameter.

    • Eric Siron says:

      The only two things that you must provide to this script are the VMName parameter and the ISOPath parameter. It will figure everything else out on its own.
      New-LinuxVM -VMName MyNewLinuxVM -ISOPath C:ISOsMyLinuxDistro.iso
      Tab-completion goes a really long way when entering values for path variables, by the way.
      The other parameters are just if you want to override something. The only thing hard-coded into the script is the number of vCPU. I should fix the script to not do that but it’s also easy to change on a VM after it’s created.

  • Jim Frenette says:

    Thanks for this article Eric. Was very helpful. One thing I ran into was that during installation setup, I had to toggle off the Security Policy so ssh would not refuse to connect. I tried disabling the firewall, making sure the sshd.service was running and listening at 0.0.0.0 on port 22, allow root login etc. and finally just ended blowing away the VM and started over. This is the iso I used: CentOS-7-x86_64-Minimal-1804.iso

  • Marcin Bojko says:

    Guys, if someone wants to have CentOS on hyper-v feel free to try my packer repo:
    https://github.com/marcinbojko/hv-packer

  • Konstantinos Georgokitsos says:

    Great article Eric! I was able to replicate that on my Win10 machine. However, trying to do the same on a (Free) Hyper-V Server from Windows Admin Center did not work out, as I am not able to see any console of the VM to perform the installation from the installation ISO. WAC only seems to let you connect with RDP, and on the CentOS installation there is obviously no RDP running yet. Any suggestions?

    As an aside, for about a year now I use Windows 10’s own ssh implementation with no problem at all to connect to linux boxes, usually from a PS sesssion. Even more recently that now works fine (for me) on the Windows Terminal beta (since a couple of weeks). There, a few months back, I could not CTRL-A D out of a screen session, but Terminal has progressed quite a bit.

    • Eric Siron says:

      WAC should connect to a Linux VM just fine. It does use RDP, but it RDPs to the host and then uses VMBus to open the VM’s console.

      • Konstantinos Georgokitsos says:

        Ok, I see. It seems to be an authentication issue in this case. WAC connects ok to the server using Administrator and password (no domain) but RDP does not work at all, not for connecting to VMs or the server itself. With the same user/pw combination. What gives?

        • Eric Siron says:

          Simple firewall problem? RDP not enabled? I always use a domain and my domain policies enable RDP access, so I have no comparison. But if you’re using WAC to connect to VMs’ consoles, then you only have to troubleshoot RDP access to the server because it brokers console connections via VMBus.

  • Petr Marek says:

    You should consider Snowflake https://github.com/subhra74/snowflake instead of putty, winscp, npp.
    It can replace all of them.

    It is a graphical SSH client. It has a file browser, terminal emulator, resource/process manager, disk space analyzer, text editor, log viewer and lots of other helpful tools, which makes it easy to work with remote servers. It runs on Linux and Windows

    I have great experience with it.

  • Jürgen says:

    Hi Eric,
    thanks for the details.
    I try to install OpenEmm 2019 Fall Release on Cent Os 7 within on my Hyper-V Server (Widows 2016 Host).
    I tried with Gen1 and Gen2 VM.

    In both Versions i am able to install the Base OS, some tools and install all components for Open EMM.
    Open EMM uses Python 2.7

    BUT i always get the same error during installation, python fails with this error message.
    “TypeError: coercing to Unicode: need string or buffer, NoneType found”

    If i do the same installation under VM Ware Workstation 15, all is fine and the installation is good.

    Do you have any idea what is wrong with Hyper-V and CentOS 7?

    • Eric Siron says:

      That reads like an install script that makes poor decisions.

      • Jürgen says:

        Hi Eric, thanks.

        One more thing.
        I have the product in an Virtual Box OVA running.

        If i install centos 7 as a hyper-v Guest and boot to the core, i am able to rsync the comple VirtualBox OVA machine to centos and after a reboot of the clone (now a hyper-v guest) the script works fine.

        • Eric Siron says:

          Doesn’t change the diagnosis.
          Two possibilities:

          1. The script makes an environment check. Either the developers did not give it a default and it returns nothing on Hyper-V, or it returns something that they did not anticipate and don’t check for.
          2. Someone at Microsoft built in a routine that watches for this script to execute, in its translated binary form, and then sabotages its memory. That routine made it through code review.

          What’s your guess?

          • Jürgen says:

            I believe in 2 but 1 seems more likely.

            The script / CentOs doesn´t like Hyper-V on Windows 2016 / 2019 (Xeon 5-2600 or Silver 4208).
            But it does work under Windows 10 in Hyper-V or VMware 12.x or 15.x (i5 6200U / i7 7600).

          • Eric Siron says:

            You genuinely believe that someone at Microsoft put in the obscene level of effort to sabotage this exact script, and their boss and team members just let that happen? Seriously? First, why??? Second, do you have any idea just how much work that would take?
            Just because something doesn’t work in one environment does not mean the environment is to blame. It is trivial to write scripts that fail like that. This script makes poor decisions. It performs an environment-dependent check of some kind and does not properly sanitize the result.

  • raja krishna kethepalli says:

    Hi Eric, Thanks for the wonderful information.

    I have an issue struggling from the last 3 days. I am able to connect to internet in browser in CentOS VM but when I try to ping google.com from terminal it is saying “Name or Service not known”. could you please let me know where the settings need to be checked or where it need to be modified.

    PS: for internet access in browser I have given an URL in network proxy settings( Automatic Proxy Configuration URL) in browser.

  • Shailen says:

    Any clues how to get shared Clipboard between the host and the guest to work?
    Windows 10 build 1809, Hyper-V
    CentOS 8.1 1911

    With VMWare, all these (including networking) just worked out of the box, but now, this Device/Credential guard is making is extremely painful to use VMware. I tried all sorts of tricks to disable this DG/CG feature but without any success.

  • Cph Media says:

    Unlike VMware, you cannot drag and drop files between the Windows host and Linux guest in Hyper-V. As you have configured the SSH server, you can transfer files from your Ubuntu VM to your Hyper-V host and do the inverse by using an SFTP (Secure File Transfer Protocol) client such as WinSCP. WinSCP uses SSH for secure connection and can also use SCP (Secure Copy Protocol) for file transferring.

  • Leuxah says:

    I have VM on Hyper-V with CentOS 8 and kernel 4.18.0. About the disk I/O scheduler at this kernel version the options are different. I’m using the option “none” (no reordering of I/O operations) in place of “noop” (inserts I/O requests into a FIFO queue). I fount this information here https://help.marklogic.com/Knowledgebase/Article/View/notes-on-io-schedulers. To set the disk I/O scheduler at boot time you need to set the “elevator=none” (or “elevator=noop”) as a kernel parameter. On CentOS 8 do this as follows and reboot:
    grub2-editenv – set “$(grub2-editenv – list | grep kernelopts) elevator=none”
    grub2-editenv – list | grep kernelopts

    • Bryan says:

      FYI, if anyone get the error grub2-editenv: error: invalid parameter “. after running this command the siply delete then readd the quotation marks.

Leave a comment or ask a question

Your email address will not be published. Required fields are marked *

Your email address will not be published. Required fields are marked *

Notify me of follow-up replies via email

Yes, I would like to receive new blog posts by email

What is the color of grass?

Please note: If you’re not already a member on the Dojo Forums you will create a new account and receive an activation email.