Rail surface defect detection is an essential part of railroad maintenance to prevent safety accidents. Recently, deep learning-based defect detection algorithms have shown impressive detection performance. However, the performance improvement from deep neural networks is based on a strong assumption that the training images have the same data distribution as the test images. This requirement is unrealistic in practical railroad surface defect detection. The appearance of rails varies significantly in different railroad sections due to changes in working conditions and maintenance status. In this paper, we propose a novel uncertainty-inspired unsupervised domain adaptation framework (UIUDA) to improve the generalization of deep learning models on data with distribution differences. Specifically, domain adversarial learning is used to align the feature distributions of training and test data. To mitigate the negative transfer caused by global alignment, we design a locally aligned domain adaptation strategy. In addition, self-training is introduced to refine the decision boundaries of the model in the test data. In this process, we propose an uncertainty-inspired evaluation method to remove noisy pseudo labels. We conducted domain adaptation experiments with RSDD and NEU-RSDD as the source domain and FRSD dataset as the target domain. The results show that UIUDA can effectively improve the generalization ability of the model, and the mIoU metric of defect segmentation is 80.17%.