Use System.Url.getOrgDomainUrl() to get the Salesforce domain URL using Apex .
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: