How to get domain URL using apex in Salesforce?

Use System.Url.getOrgDomainUrl() to get domain URL using apex in Salesforce. 

Use getOrgDomainUrl() in orgs with or without My Domain to retrieve canonical URLs. For example: https://yourDomain.my.salesforce.com, or, for orgs without My Domain enabled https://yourInstance.salesforce.com.

Sample Code:
System.debug( 'Domain URL is ' + System.Url.getOrgDomainUrl() );

Output: